相信在大部分的web專案中都會有匯出匯入Excel的需求,之前我也寫過一篇匯出單個sheet工作表的文章,沒看過的小夥伴可以去看哈,連結也給大家放出來了:匯出單個sheet
但是在我們日常的工作中,需求往往沒這麼簡單,可能需要將資料按型別分類匯出或者資料量過大,需要分多張表匯出等等。遇到類似的需求該怎麼辦呢,別慌,往下看。
pom檔案中,新增以下依賴
<!--Excel工具-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>5.2.2</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.2.2</version>
<scope>compile</scope>
</dependency>
1.ExportSheetUtil
package com.***.excel;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.springframework.http.MediaType;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.List;
/**
* @description: excel匯出多個sheet工具類
* @author: ***
* @date: 2022/9/15
*/
public class ExportSheetUtil {
/**
* 拆解並匯出多重Excel
*/
public static void exportManySheetExcel(String fileName, List<ExcelSheet> mysheets, HttpServletResponse response) {
//建立工作薄
HSSFWorkbook wb = new HSSFWorkbook();
//表頭樣式
HSSFCellStyle style = wb.createCellStyle();
// 垂直
style.setVerticalAlignment(VerticalAlignment.CENTER);
// 水平
style.setAlignment(HorizontalAlignment.CENTER);
//字型樣式
HSSFFont fontStyle = wb.createFont();
fontStyle.setFontName("微軟雅黑");
fontStyle.setFontHeightInPoints((short) 12);
style.setFont(fontStyle);
for (ExcelSheet excel : mysheets) {
//新建一個sheet
//獲取該sheet名稱
HSSFSheet sheet = wb.createSheet(excel.getFileName());
//獲取sheet的標題名
String[] handers = excel.getHanders();
//第一個sheet的第一行為標題
HSSFRow rowFirst = sheet.createRow(0);
//寫標題
for (int i = 0; i < handers.length; i++) {
//獲取第一行的每個單元格
HSSFCell cell = rowFirst.createCell(i);
//往單元格里寫資料
cell.setCellValue(handers[i]);
//加樣式
cell.setCellStyle(style);
//設定每列的列寬
sheet.setColumnWidth(i, 4000);
}
//寫資料集
List<String[]> dataset = excel.getDataset();
for (int i = 0; i < dataset.size(); i++) {
//獲取該物件
String[] data = dataset.get(i);
//建立資料行
HSSFRow row = sheet.createRow(i + 1);
for (int j = 0; j < data.length; j++) {
//設定對應單元格的值
row.createCell(j).setCellValue(data[j]);
}
}
}
// 下載檔案谷歌檔名會亂碼,用IE
try {
response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName + ".xlsx", "utf-8"));
response.setHeader("Cache-Control", "No-cache");
response.flushBuffer();
wb.write(response.getOutputStream());
wb.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
2.ExcelSheet
package com.***.excel;
import lombok.Data;
import java.util.List;
/**
* @description: 匯出多個sheet表
* @author: ***
* @date: 2022/9/15
*/
@Data
public class ExcelSheet {
/*** sheet的名稱*/
private String fileName;
/*** sheet裡的標題*/
private String[] handers;
/*** sheet裡的資料集*/
private List<String[]> dataset;
public ExcelSheet(String fileName, String[] handers, List<String[]> dataset) {
this.fileName = fileName;
this.handers = handers;
this.dataset = dataset;
}
}
1.service層
/*** 匯出開票及運單資訊*/
ExportInvoiceAndBillVo exportInvoiceAndBillInfo(InvoiceReviewListDto dto);
2.impl實現類
實現類裡的程式碼,需要各位根據自己的業務場景進行改動,無非就是將需要匯出的資料先查出來,帶入模板中,呼叫工具類的方法匯出。
package com.***.vo.invoicereview;
import lombok.Data;
import java.io.Serializable;
import java.util.List;
/**
* @description: 匯出開票和運單資訊Vo
* @author: ***
* @date: 2022/9/19
*/
@Data
public class ExportInvoiceAndBillVo implements Serializable {
/*** 開票資訊*/
private List<String[]> invoiceList;
/*** 運單資訊*/
private List<String[]> billList;
}
@Override
public ExportInvoiceAndBillVo exportInvoiceAndBillInfo(InvoiceReviewListDto dto) {
ExportInvoiceAndBillVo invoiceAndBill = new ExportInvoiceAndBillVo();
// 查詢需要匯出的開票資訊
PageInfo<InvoiceReviewListVo> pageInfo = queryInvoiceReviewList(dto);
List<InvoiceReviewListVo> invoiceList = pageInfo.getList();
if (invoiceList.size() > 10000) {
throw new ServiceException("開票資料過多,請分批次匯出");
}
// 查詢需要匯出的車運運單資訊
List<Long> invoiceIdList = invoiceList.stream().map(InvoiceReviewListVo::getInvoiceId).collect(Collectors.toList());
List<ExportBillVo> billList = getBillInfo(invoiceIdList);
if (billList.size() > 10000) {
throw new ServiceException("運單資料過多,請分批次匯出");
}
// 將表1 表2的資料 放入定義的物件Vo中
invoiceAndBill.setInvoiceList(getInvoiceDataList(invoiceList));
invoiceAndBill.setBillList(getBillDataList(billList));
return invoiceAndBill;
}
3.controller層
controller層的程式碼需要注意的是:
1.因為匯出Excel一般都是通過瀏覽器進行下載的,所以入參中需要加入HttpServletResponse
2.呼叫封裝的工具類ExportSheetUtil中的exportManySheetExcel方法就可以了
3.表頭和表名需要各位根據自身的業務場景修改哈
/**
* 匯出開票和運單資訊
*/
@Log
@PostMapping("/exportInvoiceAndBillInfo")
public void exportInvoiceAndBillInfo(@RequestBody InvoiceReviewListDto dto, HttpServletResponse response) {
ExportInvoiceAndBillVo invoiceAndBillVo = invoiceFacadeService.exportInvoiceAndBillInfo(dto);
//設定sheet的表頭與表名
String[] invoiceSheetHead = {"開票編號", "票號", "公司名稱", "收票方名稱", "結算型別", "納稅識別碼", "收票聯絡人", "聯絡人電話", "運單總金額(元)", "含稅總金額(元)", "開票狀態", "提交開票時間", "運營稽核時間", "運營稽核人", "財務稽核時間", "財務稽核人", "開票完成時間", "沖銷操作人", "沖銷時間"};
String[] billSheetHead = {"開票編號", "運單號", "發貨地", "收貨地", "司機", "司機電話", "貨物名稱", "貨物數量", "單位", "貨物重量(噸)", "運單狀態", "運單金額(元)", "含稅金額(元)"};
ExcelSheet invoiceExcel = new ExcelSheet("開票資訊", invoiceSheetHead, invoiceAndBillVo.getInvoiceList());
ExcelSheet billExcel = new ExcelSheet("運單資訊", billSheetHead, invoiceAndBillVo.getBillList());
List<ExcelSheet> mysheet = new ArrayList<>();
mysheet.add(invoiceExcel);
mysheet.add(billExcel);
ExportSheetUtil.exportManySheetExcel("開票及運單資訊", mysheet, response);
}
最終匯出的Excel檔案: