前段時間項目需要將用戶操作日誌表導出爲Excel,上網搜了幾篇文章參考,最終實現了。這裏記錄下代碼,避免以後實現一樣的功能時再上網去搜。
導入以下兩個依賴:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
controller層:
@GetMapping("/export")
public void export(HttpServletResponse response) throws IOException {
operationLogService.export(response);
}
service層:
public void export(HttpServletResponse response) throws IOException {
HSSFWorkbook workbook = new HSSFWorkbook();
//sheet名稱
HSSFSheet sheet = workbook.createSheet("用戶操作日誌表");
//獲取表數據,根據自己實際情況獲取
List<OperationLog> logList = operationLogDao.listAll();
//設置要導出的文件的名字
String fileName = "用戶操作日誌" + ".xls";
//新增數據行,並且設置單元格數據
int rowNum = 1;
String[] headers = {"id", "模塊", "姓名", "訪問時間", "IP地址", "操作內容"};
//headers表示excel表中第一行的表頭
HSSFRow row = sheet.createRow(0);
//在excel表中添加表頭
for (int i = 0; i < headers.length; i++) {
HSSFCell cell = row.createCell(i);
HSSFRichTextString text = new HSSFRichTextString(headers[i]);
cell.setCellValue(text);
}
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//在表中存放查詢到的數據放入對應的列
for (OperationLog operationLog : logList) {
HSSFRow row1 = sheet.createRow(rowNum);
row1.createCell(0).setCellValue(operationLog.getId());
row1.createCell(1).setCellValue(operationLog.getModule());
row1.createCell(2).setCellValue(operationLog.getUserName());
row1.createCell(3).setCellValue(format.format(operationLog.getLogTime()));
row1.createCell(4).setCellValue(operationLog.getIp());
row1.createCell(5).setCellValue(operationLog.getContent());
rowNum++;
}
//設置自動列寬
for (int i = 0; i < headers.length; i++) {
sheet.autoSizeColumn(i);
sheet.setColumnWidth(i, sheet.getColumnWidth(i) * 13 / 10);
}
response.setContentType("application/octet-stream;charset=UTF-8");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
workbook.write(response.getOutputStream());
}
最後直接用瀏覽器調即可。