之前项目中要完成基于Excel模板下载的实现功能(完成数据统计).现在总结整理一下.
环境搭建:IDEA+Maven+SpringBoot+BootStrap+Thymeleaf+Mysql+Excel+MyBatis+Lombok+IDEA热部署
项目的工程结构如下:
首先编写Maven依赖如下:
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.10.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<!-- set thymeleaf version -->
<thymeleaf.version>3.0.0.RELEASE</thymeleaf.version>
<thymeleaf-layout-dialect.version>2.0.0</thymeleaf-layout-dialect.version>
</properties>
<dependencies>
<!-- 引入Web依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 引入Thymeleaf-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- 引入actuator-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!-- 热部署-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<!-- lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.18</version>
</dependency>
<!-- 添加MySql的依赖-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.0.8</version>
</dependency>
<!--配置这个可以使鼠标点击就可以到那个配置类的 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<!-- 引入druid数据库连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.9</version>
</dependency>
<!-- MyBatis的依赖-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
<!-- jsp -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>
<!-- 处理Excel2003-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<!-- 处理Excel2007-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<fork>true</fork>
</configuration>
</plugin>
</plugins>
</build>
</project>
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<Bill> selectBillList();
}
ExportService
public interface ExportService {
/**
* 查询出所有的票据列表
* @return
*/
List<Bill> loadBillList();
}
ExportServiceImpl
@Service
public class ExportServiceImpl implements ExportService{
@Autowired
private BillMapper billMapper;
@Override
public List<Bill> loadBillList() {
List<Bill> 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<Bill> 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.size();i++){
bill=list.get(i);
// 5.创建单元格的行
row=sheet.createRow(i);
// 6.设置单元格属性值和样式
row.createCell(0).setCellStyle(cellStyle);
row.createCell(0).setCellValue(bill.getBillNo());
row.createCell(1).setCellStyle(cellStyle);
row.createCell(1).setCellValue(bill.getBank());
row.createCell(2).setCellStyle(cellStyle);
row.createCell(2).setCellValue(bill.getWightedAverageYield().toString());
row.createCell(3).setCellStyle(cellStyle);
row.createCell(3).setCellValue(bill.getFaceBillAmt().toString());
row.createCell(4).setCellStyle(cellStyle);
row.createCell(4).setCellValue(bill.getRepairDate());
}
// 7.设置sheet名称和单元格内容
wb.setSheetName(0,"票据报表");
try
{
// 8.将Excel写入到输出流里面
wb.write(out);
}
catch (Exception e)
{
e.printStackTrace();
}
}
/**
* 根据Excel模板来导出Excel数据
* @param out
* @param list
*/
private void templateExport(OutputStream out, List<Bill> 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<list.size();i++){
bill=list.get(i);
// 5.得到第三行
row=sheet.getRow(i+3);
// 6.设置单元格属性值和样式
row.getCell(0).setCellValue(bill.getBillNo());
row.getCell(1).setCellValue(bill.getBank());
row.getCell(2).setCellValue(bill.getFaceBillAmt().setScale(2,BigDecimal.ROUND_HALF_UP)+"");
row.getCell(3).setCellValue(bill.getWightedAverageYield().multiply(new BigDecimal(100))+"%");
row.getCell(4).setCellValue(bill.getRepairDate());
}
// 7.设置sheet名称和单元格内容
wb.setSheetName(0,"票据报表");
try
{
// 8.将Excel写入到输出流里面
wb.write(out);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 定义别名,基于包的形式-->
<typeAliases>
<package name="com.example.demo.entity" />
</typeAliases>
</configuration>
billMapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.demo.mapper.BillMapper">
<resultMap id="billResultMap" type="com.example.demo.entity.Bill">
<id column="id" property="id" jdbcType="INTEGER" />
<result column="bill_no" property="billNo" jdbcType="VARCHAR" />
<result column="bank" property="bank" jdbcType="VARCHAR" />
<result column="wighted_average_yield" property="wightedAverageYield" jdbcType="DECIMAL" />
<result column="face_bill_amt" property="faceBillAmt" jdbcType="DECIMAL" />
<result column="repair_date" property="repairDate" jdbcType="VARCHAR" />
</resultMap>
<!-- 使用sql片段-->
<sql id="BASE_COLUMN_LIST">
id,
bill_no,
bank,
wighted_average_yield,
face_bill_amt,
repair_date
</sql>
<!-- 查询票据列表-->
<select id="selectBillList" resultMap="billResultMap">
SELECT
<include refid="BASE_COLUMN_LIST" />
FROM BILL_LIST
</select>
</mapper>
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
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" >
<head>
<meta charset="UTF-8">
<title>报表展示</title>
<link rel="stylesheet" th:href="@{/bootstrap/css/bootstrap.min.css}" />
<link rel="stylesheet" th:href="@{/bootstrap/css/bootstrap-theme.min.css}" />
<style type="text/css">
h2{
color:#985f0d;
}
#connection{
position: absolute;
right:0;
}
</style>
</head>
<body>
<div align="center">
<h2 >银行金融承兑报表展示</h2>
</div>
<br/>
<div class="bs-example" data-example-id="striped-table">
<table class="table table-bordered table-hover">
<thead>
<tr>
<th score="row"></th>
<th>票据编号</th>
<th>承兑银行</th>
<th>贴现率</th>
<th>票面金额</th>
<th>到账时间</th>
</tr>
</thead>
<tbody>
<tr th:each="list,listStat : ${listData}" >
<th th:text="${listStat.index+1}">索引号</th>
<td th:text="${list.billNo}">Otto</td>
<td th:text="${list.bank}">Otto</td>
<td th:text="${#numbers.formatDecimal(list.wightedAverageYield*100, 0, 4)+'%'}">@mdo</td>
<td th:text="${'¥'+#numbers.formatDecimal(list.faceBillAmt,0, 2)}">Otto</td>
<td th:text="${list.repairDate}">@mdo</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="3">
<a href="/export/doExport" class="btn btn-success">导出报表</a>
</td>
<td colspan="3">
<a id="connection" href="https://www.lixingblog.com" class="btn btn-success">联系我们</a>
</td>
</tr>
</tfoot>
</table>
</div>
</body>
</html>
Excel模板templates.xlsx
数据库的数据是一些测试数据.
运行测试结果:
点击导出报表按钮即可实现导出功能.查看下载数据.
不能跳转页面后的.
一句话,下载Excel就是将Excel写入输出流即可完成实现功能.整体功能比较简单当做复习整理的.