更新時間:2023-08-17 來源:黑馬程序員 瀏覽量:
Apache POI 是一個處理Miscrosoft Office各種文件格式的開源項目。簡單來說就是,我們可以使用 POI 在 Java 程序中對Miscrosoft Office各種文件進行讀寫操作。
一般情況下,POI 都是用于操作 Excel 文件,例如銀行網(wǎng)銀系統(tǒng)導出交易明細、各種業(yè)務系統(tǒng)導出Excel報表、批量導入業(yè)務數(shù)據(jù)等。
POI導出Excel報表的需求分析和設計
如下產(chǎn)品原型,我們要在導出的報表中包含各模塊的業(yè)務數(shù)據(jù)和明細。
導出的Excel報表格式:
導出Excel形式的報表文件和最近30天的運營數(shù)據(jù),接口可以如下設計:
當前接口沒有返回數(shù)據(jù),因為報表導出功能本質上是文件下載,服務端會通過輸出流將Excel文件下載到客戶端瀏覽器。實現(xiàn)步驟如下:
①設計Excel模板文件
②查詢近30天的運營數(shù)據(jù)
③將查詢到的運營數(shù)據(jù)寫入模板文件
④通過輸出流將Excel文件下載到客戶端瀏覽器
根據(jù)接口定義,在ReportController中創(chuàng)建export方法:
/**
* 導出運營數(shù)據(jù)報表
* @param response
*/@GetMapping("/export")
@ApiOperation("導出運營數(shù)據(jù)報表")
public void export(HttpServletResponse response){
reportService.exportBusinessData(response);
}
在ReportService接口中聲明導出運營數(shù)據(jù)報表的方法:
/**
* 導出近30天的運營數(shù)據(jù)報表
* @param response
*/
void exportBusinessData(HttpServletResponse response);
在ReportService接口中聲明導出運營數(shù)據(jù)報表的方法:
/**
* 導出近30天的運營數(shù)據(jù)報表
* @param response
*/
public void exportBusinessData(HttpServletResponse response) {
LocalDate begin = LocalDate.now().minusDays(30);
LocalDate end = LocalDate.now().minusDays(1);
//查詢概覽運營數(shù)據(jù),提供給Excel模板文件
BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(begin,LocalTime.MIN), LocalDateTime.of(end, LocalTime.MAX));
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("template/運營數(shù)據(jù)報表模板.xlsx");
try {
//基于提供好的模板文件創(chuàng)建一個新的Excel表格對象
XSSFWorkbook excel = new XSSFWorkbook(inputStream);
//獲得Excel文件中的一個Sheet頁
XSSFSheet sheet = excel.getSheet("Sheet1");
在ReportServiceImpl實現(xiàn)類中實現(xiàn)導出運營數(shù)據(jù)報表的方法(第2部分):
sheet.getRow(1).getCell(1).setCellValue(begin + "至" + end);
//獲得第4行XSSFRow row = sheet.getRow(3);
//獲取單元格row.getCell(2).setCellValue(businessData.getTurnover());
row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
row.getCell(6).setCellValue(businessData.getNewUsers());
row = sheet.getRow(4);row.getCell(2).setCellValue(businessData.getValidOrderCount());
row.getCell(4).setCellValue(businessData.getUnitPrice());
for (int i = 0; i < 30; i++) {
LocalDate date = begin.plusDays(i);
//準備明細數(shù)據(jù)
businessData = workspaceService.getBusinessData(LocalDateTime.of(date,、
LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
row = sheet.getRow(7 + i);
在ReportServiceImpl實現(xiàn)類中實現(xiàn)導出運營數(shù)據(jù)報表的方法(第3部分):
row.getCell(1).setCellValue(date.toString());
row.getCell(2).setCellValue(businessData.getTurnover());
row.getCell(3).setCellValue(businessData.getValidOrderCount());
row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
row.getCell(5).setCellValue(businessData.getUnitPrice());
row.getCell(6).setCellValue(businessData.getNewUsers());
}
//通過輸出流將文件下載到客戶端瀏覽器中
ServletOutputStream out = response.getOutputStream();
excel.write(out);
//關閉資源
out.flush();
out.close();
excel.close();
} catch (IOException e) {
e.printStackTrace();
}
}