SpringBoot基于Excel模板完成下载

之前项目中要完成基于Excel模板下载的实现功能(完成数据统计).现在总结整理一下.

环境搭建:IDEA+Maven+SpringBoot+BootStrap+Thymeleaf+Mysql+Excel+MyBatis+Lombok+IDEA热部署

项目的工程结构如下:

SpringBoot基于Excel模板完成下载_第1张图片

SpringBoot基于Excel模板完成下载_第2张图片

SpringBoot基于Excel模板完成下载_第3张图片

SpringBoot基于Excel模板完成下载_第4张图片

首先编写Maven依赖如下:

4.0.0
	com.example
	demo
	0.0.1-SNAPSHOT
	jar
	demo
	Demo project for Spring Boot
	
		org.springframework.boot
		spring-boot-starter-parent
		1.5.10.RELEASE
		 
	
	
		UTF-8
		UTF-8
		1.8
        
        3.0.0.RELEASE
        2.0.0
	
	
        
        
            org.springframework.boot
            spring-boot-starter-web
        
        
        
            org.springframework.boot
            spring-boot-starter-thymeleaf
        
        
		
			org.springframework.boot
			spring-boot-starter-actuator
		
		
		
			org.springframework.boot
			spring-boot-devtools
			true
		
        
        
            org.projectlombok
            lombok
            1.16.18
        
        
        
            mysql
            mysql-connector-java
            5.0.8
        
        
        
            org.springframework.boot
            spring-boot-configuration-processor
            true
        
        
        
            com.alibaba
            druid
            1.1.9
        
        
        
            org.mybatis.spring.boot
            mybatis-spring-boot-starter
            1.3.1
        
        
        
            javax.servlet
            jsp-api
            2.0
            provided
        
        
        
            org.apache.poi
            poi
            3.17
        
		
		
			org.apache.poi
			poi-ooxml
			3.17
		
		
			org.springframework.boot
			spring-boot-starter-test
			test
		
	
	
		
			
				org.springframework.boot
				spring-boot-maven-plugin
                
                    true
                
			
		
	

sql的建表语句如下:

CREATE TABLE `bill_list` (
  `id` int(11) NOT NULL,
  `bill_no` varchar(30) NOT NULL,
  `bank` varchar(30) NOT NULL,
  `wighted_average_yield` decimal(6,4) NOT NULL,
  `face_bill_amt` decimal(10,2) NOT NULL,
  `repair_date` varchar(10) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Bill实体类

@Setter
@Getter
public class Bill {
    /** 数据id*/
    private Integer id;
    /** 票据编号**/
    private String billNo;
    /** 承兑银行**/
    private String bank;
    /** 贴现率**/
    private BigDecimal wightedAverageYield;
    /** 票面金额**/
    private BigDecimal faceBillAmt;
    /** 到期日**/
    private String repairDate;

}

BillMapper接口

@Repository
public interface BillMapper {
    /**
     * 查询票据列表
     * @return
     */
    List selectBillList();

}

ExportService

public interface ExportService {
    /**
     * 查询出所有的票据列表
     * @return
     */
    List loadBillList();
}

ExportServiceImpl

@Service
public class ExportServiceImpl implements  ExportService{
    @Autowired
    private BillMapper billMapper;
    @Override
    public List loadBillList() {
        List list=billMapper.selectBillList();
        return list;
    }
}

BillController

import com.example.demo.entity.Bill;
import com.example.demo.service.ExportService;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.util.List;
/**
 * title: com.example.demo.controller
 * @author 
 * date: 
 * description: 票据业务控制器
 */
@Controller
@RequestMapping("/export")
public class BillController {
    private static final String TO_PATH="export";
    @Autowired
    private ExportService exportService;
    /**
     * 查询所有票据列表
     * @return
     */
    @RequestMapping("/toList")
    public ModelAndView show(){
        ModelAndView view=new ModelAndView();
        view.addObject("listData",exportService.loadBillList());
        view.setViewName(TO_PATH);
        return view;
    }

    /**
     * 导出查询报表
     */
    @RequestMapping("/doExport")
    public void doExport(HttpServletResponse response){
        String fileName="票据报表";
        try {
            response.setHeader("Content-type","application/vnd.ms-excel");
            // 解决导出文件名中文乱码
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Disposition","attachment;filename="+new String(fileName.getBytes("UTF-8"),"ISO-8859-1")+".xls");
            // 模板导出Excel
            templateExport(response.getOutputStream(), exportService.loadBillList());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 将生成的Excel写入到输出流里面
     * @param out
     */
    private void getExport(OutputStream out, List list){
        // 1.创建Excel工作薄对象
        HSSFWorkbook wb = new HSSFWorkbook();
        // 2.创建Excel工作表对象
        HSSFSheet sheet = wb.createSheet("票据列表");
        // 3.创建单元格
        CellStyle cellStyle =wb.createCellStyle();
        // 4.设置单元格的样式
        cellStyle.setFillForegroundColor(HSSFColor.SKY_BLUE.index);
        HSSFRow row;
        Bill bill;
        for(int i=0;i list) throws IOException {
        // 1.读取Excel模板
        File file= ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX+"static/excel/template.xlsx");
        InputStream in=new FileInputStream(file);
        XSSFWorkbook wb=new XSSFWorkbook(in);
        // 2.读取模板里面的所有Sheet
        XSSFSheet sheet=wb.getSheetAt(0);
        // 3.设置公式自动读取
        sheet.setForceFormulaRecalculation(true);
        // 4.向相应的单元格里面设置值
        XSSFRow row;
        Bill bill;
        for(int i=0;i

mybatis-config.xml




    
    
         
    

billMapper.xml




    
        
        
        
        
        
        
    
    
    
       id,
       bill_no,
       bank,
       wighted_average_yield,
       face_bill_amt,
       repair_date
    
    
    

application.properties

server.port =9999
spring.application.name=Demo web
management.security.enabled=false
spring.thymeleaf.suffix=.html  
spring.thymeleaf.mode=HTML5
spring.thymeleaf.content-type=text/html  
spring.thymeleaf.cache=false  
spring.resources.chain.strategy.content.enabled=true  
spring.resources.chain.strategy.content.paths=/**  
#MySQL的依赖
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=479602
spring.datasource.url=jdbc:mysql://localhost:3306/testssm?useUnicode=true&characterEncoding=utf-8
#配置MyBatis的依赖
mybatis.mapper-locations=classpath:mybatis/mapper/*Mapper.xml
mybatis.config-location=classpath:mybatis/mybatis-config.xml
#配置数据库连接池druid
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
#最大活跃数
spring.datasource.maxActive=20
#初始化数量
spring.datasource.initialSize=1
#最大连接等待超时时间
spring.datasource.maxWait=60000
#打开PSCache,并且指定每个连接PSCache的大小
spring.datasource.poolPreparedStatements=true
spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
#通过connectionProperties属性来打开mergeSql功能;慢SQL记录
#connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
spring.datasource.minIdle=1
spring.datasource.timeBetweenEvictionRunsMillis=60000
spring.datasource.minEvictableIdleTimeMillis=300000
spring.datasource.validationQuery=select 1 from dual
spring.datasource.testWhileIdle=true
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false
#配置监控统计拦截的filters,去掉后监控界面sql将无法统计,'wall'用于防火墙
filters=stat, wall, log4j

export.html




    
    报表展示
    
    
    


   

银行金融承兑报表展示


票据编号 承兑银行 贴现率 票面金额 到账时间
索引号 Otto Otto @mdo Otto @mdo
导出报表 联系我们

Excel模板templates.xlsx

SpringBoot基于Excel模板完成下载_第5张图片

数据库的数据是一些测试数据.

SpringBoot基于Excel模板完成下载_第6张图片

运行测试结果:

SpringBoot基于Excel模板完成下载_第7张图片

点击导出报表按钮即可实现导出功能.查看下载数据.

SpringBoot基于Excel模板完成下载_第8张图片

不能跳转页面后的.

SpringBoot基于Excel模板完成下载_第9张图片

一句话,下载Excel就是将Excel写入输出流即可完成实现功能.整体功能比较简单当做复习整理的.

你可能感兴趣的:(MyBatis框架,SpringBoot框架,SpringBoot项目实战)