我們查到的數據是list,如何將這些數據導出到Excel表格中呢
我這裏查到的list數據是 List monthReportModels
一、導入依賴
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.6</version>
</dependency>
二、生成表格
根據數據以及一些屬性,生成表格,並設置表格的一些屬性
public HSSFWorkbook getHSSFWorkbook(String sheetName, String[] title, String[][] values, HSSFWorkbook workbook) {
// 創建一個HSSFWorkbook,對應一個Excel文件
if (workbook == null) {
workbook = new HSSFWorkbook();
}
// 在workbook中添加一個sheet,對應Excel文件中的sheet
HSSFSheet sheet = workbook.createSheet(sheetName);
// 在sheet中添加表頭第0行
HSSFRow row = sheet.createRow(0);
// 創建單元格,並設置值表頭 設置表頭居中
HSSFCellStyle cellStyle = workbook.createCellStyle();
cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
// 聲明列對象
HSSFCell cell = null;
// 創建標題
for (int i = 0; i < title.length; i++) {
cell = row.createCell(i);
cell.setCellValue(title[i]);
cell.setCellStyle(cellStyle);
}
// 創建內容
for (int i = 0; i < values.length; i++) {
row = sheet.createRow(i + 1);
for (int j = 0; j < values[i].length; j++) {
// 將內容按順序賦給對應的列對象
row.createCell(j).setCellValue(values[i][j]);
}
}
return workbook;
}
三、設置發送響應流
public void setResponseHeader(HttpServletResponse response, String fileName) {
try {
fileName = new String(fileName.getBytes(), "ISO8859-1");
response.setContentType("application/octet-stream;charset=ISO8859-1");
response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
response.addHeader("Pargam", "no-cache");
response.addHeader("Cache-Control", "no-cache");
} catch (Exception e) {
e.printStackTrace();
}
}
四、處理list數據
將list數據處理成二維數組,設置Excel標題,以及Excel文件名,Excel的Sheet名,以供生成表格
public void exportExcel(HttpServletResponse response, List<MonthReportModel> monthReportModels) {
// Excel標題
String[] title = {"姓名", "違紀次數", "違紀原因", "請假次數", "請假類型", "請假累計時間(小時)", "請假原因描述"};
// Excel文件名
String fileName = "請假統計.xls";
// sheet名
String sheetName = "請假統計";
// 將數據放到數組中
String[][] content = new String[monthReportModels.size()][title.length];
for (int i = 0; i < monthReportModels.size(); i++) {
MonthReportModel monthReportModel = monthReportModels.get(i);
content[i][0] = monthReportModel.getUserName();
content[i][1] = monthReportModel.getDisobedientNum();
content[i][2] = monthReportModel.getDisobedientReason();
content[i][3] = monthReportModel.getLeaveNum();
content[i][4] = monthReportModel.getLeaveType();
content[i][5] = monthReportModel.getLeaveTime() + "小時";
content[i][6] = monthReportModel.getLeaveReason();
}
// 導出Excel
try {
HSSFWorkbook hssfWorkbook = getHSSFWorkbook(sheetName, title, content, null);
setResponseHeader(response, fileName);
OutputStream outputStream = response.getOutputStream();
hssfWorkbook.write(outputStream);
outputStream.flush();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}