Spring boot實現匯出資料生成excel檔案返回
阿新 • • 發佈:2019-01-09
一、基於框架
1.IDE
- IntelliJ IDEA
2.軟體環境
- Spring boot
- mysql
- mybatis
- org.apache.poi
二、環境整合
1.建立spring boot專案工程
略過
2.maven引入poi
<!--資料匯出依賴 excel-->
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
<groupId>org. apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml-schemas -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>3.17</version>
< /dependency>
<!--資料匯出依賴 End excel-->
三、程式碼實現
此處以匯出雲端mysql資料中的使用者表為例(資料為虛假資料)
1.配置xls表格表頭
此處我建立一個class(ColumnTitleMap)來維護需要匯出的mysql表和xls表頭顯示的關係
程式碼註釋已經清晰明瞭,就不再贅述
/**
* @desc:資料匯出,生成excel檔案時的列名稱集合
* @author: chao
* @time: 2018.6.11
*/
public class ColumnTitleMap {
private Map<String, String> columnTitleMap = new HashMap<String, String>();
private ArrayList<String> titleKeyList = new ArrayList<String> ();
public ColumnTitleMap(String datatype) {
switch (datatype) {
case "userinfo":
initUserInfoColu();
initUserInfoTitleKeyList();
break;
default:
break;
}
}
/**
* mysql使用者表需要匯出欄位--顯示名稱對應集合
*/
private void initUserInfoColu() {
columnTitleMap.put("id", "ID");
columnTitleMap.put("date_create", "註冊時間");
columnTitleMap.put("name", "名稱");
columnTitleMap.put("mobile", "手機號");
columnTitleMap.put("email", "郵箱");
columnTitleMap.put("pw", "密碼");
columnTitleMap.put("notice_voice", "語音通知開關");
columnTitleMap.put("notice_email", "郵箱通知開關");
columnTitleMap.put("notice_sms", "簡訊通知開關");
columnTitleMap.put("notice_push", "應用通知開關");
}
/**
* mysql使用者表需要匯出欄位集
*/
private void initUserInfoTitleKeyList() {
titleKeyList.add("id");
titleKeyList.add("date_create");
titleKeyList.add("name");
titleKeyList.add("mobile");
titleKeyList.add("email");
titleKeyList.add("pw");
titleKeyList.add("notice_voice");
titleKeyList.add("notice_email");
titleKeyList.add("notice_sms");
titleKeyList.add("notice_push");
}
public Map<String, String> getColumnTitleMap() {
return columnTitleMap;
}
public ArrayList<String> getTitleKeyList() {
return titleKeyList;
}
}
2.controller
提供對外介面,ExportDataController.java
package com.mcrazy.apios.controller;
import com.mcrazy.apios.service.ExportDataService;
import com.mcrazy.apios.service.UserInfoService;
import com.mcrazy.apios.util.datebase.columntitle.ColumnTitleMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* @desc:資料匯出api控制器
* @author: chao
* @time: 2018.6.11
*/
@Controller
@RequestMapping(value = "/exportdata")
public class ExportDataController {
@Autowired
UserInfoService userInfoService;
@Autowired
ExportDataService exportDataService;
/**
* @api: /apios/exportdata/excel/
* @method: GET
* @desc: 匯出資料,生成xlsx檔案
* @param response 返回物件
* @param time_start 篩選時間,開始(預留,查詢時並未做篩選資料處理)
* @param end_start 篩選時間,結束(預留,查詢時並未做篩選資料處理)
*/
@GetMapping(value = "/excel")
public void getUserInfoEx(
HttpServletResponse response,
@RequestParam(required = true) String time_start,
@RequestParam(required = true) String end_start
) {
try {
List<Map<String,Object>> userList = userInfoService.queryUserInfoResultListMap();
ArrayList<String> titleKeyList= new ColumnTitleMap("userinfo").getTitleKeyList();
Map<String, String> titleMap = new ColumnTitleMap("userinfo").getColumnTitleMap();
exportDataService.exportDataToEx(response, titleKeyList, titleMap, userList);
} catch (Exception e) {
//
System.out.println(e.toString());
}
}
}
3.service
(1).使用者表資料
- UserInfoMapper.java
package com.mcrazy.apios.mapper;
import com.mcrazy.apios.model.UserInfo;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
import java.util.Map;
@Mapper
public interface UserInfoMapper {
/**
* @desc 查詢所有使用者資訊
* @return 返回多個使用者List
* */
List<Map<String,Object>> queryUserInfoResultListMap();
}
- UserInfoMapper.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.mcrazy.apios.mapper.UserInfoMapper">
<select id="queryUserInfoResultListMap" resultType="HashMap">
select * from user_info
</select>
</mapper>
- UserInfoService.java
package com.mcrazy.apios.service;
import com.mcrazy.apios.mapper.UserInfoMapper;
import com.mcrazy.apios.model.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
@Service
public class UserInfoService {
@Autowired
UserInfoMapper userInfoMapper;
/**
* @desc 查詢所有使用者資訊
* @return 返回多個使用者List
* */
public List<Map<String,Object>> queryUserInfoResultListMap() {
List<Map<String,Object>> list = userInfoMapper.queryUserInfoResultListMap();
return list;
}
}
(2). 生成excel檔案和匯出
- ExportDataService.java
package com.mcrazy.apios.service;
import com.mcrazy.apios.util.datebase.ExportExcelUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* @desc:資料匯出服務
* @author: chao
* @time: 2018.6.11
*/
@Service
public class ExportDataService {
@Autowired
ExportExcelUtil exportExcelUtil;
/*匯出使用者資料表*/
public void exportDataToEx(HttpServletResponse response, ArrayList<String> titleKeyList, Map<String, String> titleMap, List<Map<String,Object>> src_list) {
try {
exportExcelUtil.expoerDataExcel(response, titleKeyList, titleMap, src_list);
} catch (Exception e) {
System.out.println("Exception: " + e.toString());
}
}
}
- 匯出工具封裝,ExportExcelUtil.java
package com.mcrazy.apios.util.datebase;
import com.mcrazy.apios.util.object.DateUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* @desc:資料匯出,生成excel檔案
* @author: chao
* @time: 2018.6.12
*/
@Service
public class ExportExcelUtil {
public void expoerDataExcel(HttpServletResponse response, ArrayList<String> titleKeyList, Map<String, String> titleMap, List<Map<String,Object>> src_list) throws IOException {
String xlsFile_name = DateUtils.currtimeToString14() + ".xlsx"; //輸出xls檔名稱
//記憶體中只建立100個物件
Workbook wb = new SXSSFWorkbook(100); //關鍵語句
Sheet sheet = null; //工作表物件
Row nRow = null; //行物件
Cell nCell = null; //列物件
int rowNo = 0; //總行號
int pageRowNo = 0; //頁行號
for (int k=0;k<src_list.size();k++) {
Map<String,Object> srcMap = src_list.get(k);
//寫入300000條後切換到下個工作表
if(rowNo%300000==0){
System.out.println("Current Sheet:" + rowNo/300000);
sheet = wb.createSheet("工作簿"+(rowNo/300000));//建立新的sheet物件
sheet = wb.getSheetAt(rowNo/300000); //動態指定當前的工作表
pageRowNo = 0; //新建了工作表,重置工作表的行號為0
// -----------定義表頭-----------
nRow = sheet.createRow(pageRowNo++);
// 列數 titleKeyList.size()
for(int i=0;i<titleKeyList.size();i++){
Cell cell_tem = nRow.createCell(i);
cell_tem.setCellValue(titleMap.get(titleKeyList.get(i)));
}
rowNo++;
// ---------------------------
}
rowNo++;
nRow = sheet.createRow(pageRowNo++); //新建行物件
// 行,獲取cell值
for(int j=0;j<titleKeyList.size();j++){
nCell = nRow.createCell(j);
if (srcMap.get(titleKeyList.get(j)) != null) {
nCell.setCellValue(srcMap.get(titleKeyList.get(j)).toString());
} else {
nCell.setCellValue("");
}
}
}
response.setContentType("application/vnd.ms-excel;charset=utf-8");
response.setHeader("Content-disposition", "attachment;filename=" + xlsFile_name);
response.flushBuffer();
OutputStream outputStream = response.getOutputStream();
wb.write(response.getOutputStream());
wb.close();
outputStream.flush();
outputStream.close();
}
}
三、執行
至此,所有程式碼工作已經做完,把程式執行起來,在瀏覽器呼叫介面,會自動下載到電腦中
- 瀏覽器開啟:
http://192.168.1.70:8080/apios/exportdata/excel/?time_start=2018-12-19&end_start=2018-12-19
- 效果
- 得到xlsx檔案,檢視資料