1. 程式人生 > >SpringBoot基於Excel模板完成下載

SpringBoot基於Excel模板完成下載

之前專案中要完成基於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寫入輸出流即可完成實現功能.整體功能比較簡單當做複習整理的.