1.導入maven
!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.15</version>
<scope>compile</scope>
</dependency>
2.導出excel方法
public void exportExcel(HttpServletResponse response, Searchable search){
//查出檢驗項目
Master master = masterService.findOne(search);
//查出檢驗項目的結果集合
List<Result> list = findListWithSort(search);
//創建HSSFWorkbook對象(excel的文檔對象)
HSSFWorkbook wb = new HSSFWorkbook();
//建立新的sheet對象(excel的表單)
HSSFSheet sheet = wb.createSheet("檢驗結果表");
//在sheet里創建第一行,參數為行索引(excel的行),可以是0~65535之間的任何一個
HSSFRow row1 = sheet.createRow(0);
//創建單元格(excel的單元格,參數為列索引,可以是0~255之間的任何一個
HSSFCell cell = row1.createCell(0);
//設置單元格內容
cell.setCellValue(master.getItemName() + "檢驗報告單");
//合並單元格CellRangeAddress構造參數依次表示起始行,截至行,起始列, 截至列
sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 5));
//在sheet里創建第二行
HSSFRow row2 = sheet.createRow(1);
/*HSSFCell cell1 = row2.createCell(0);
HSSFCell cell2 = row2.createCell(1);
HSSFCell cell3 = row2.createCell(2);
HSSFCell cell4 = row2.createCell(3);
HSSFCell cell5 = row2.createCell(4);
HSSFCell cell6 = row2.createCell(5);
//設置列寬
sheet.setColumnWidth( cell1.getColumnIndex(),256 * 25);
sheet.setColumnWidth( cell2.getColumnIndex(),256 * 20);
sheet.setColumnWidth( cell3.getColumnIndex(),256 * 20);
sheet.setColumnWidth( cell4.getColumnIndex(),256 * 20);
sheet.setColumnWidth( cell5.getColumnIndex(),256 * 20);
sheet.setColumnWidth( cell6.getColumnIndex(),256 * 20);*/
//設置缺省列寬
sheet.setDefaultColumnWidth(20);
//設置缺省列高
sheet.setDefaultRowHeightInPoints(30);
//創建單元格並設置單元格內容
row2.createCell(0).setCellValue("報告日期");
HSSFCellStyle style = wb.createCellStyle();
// 實例化樣式對象
row2.createCell(1).setCellValue("報告項目名稱");
// 垂直居中
style.setAlignment(HorizontalAlignment.CENTER);
//將樣式應用到行
cell.setCellStyle(style);
row2.createCell(2).setCellValue("結果");
row2.createCell(3).setCellValue("單位");
row2.createCell(4).setCellValue("異常");
row2.createCell(5).setCellValue("正常參考值");
for (int i = 0; i < list.size(); i++) {
HSSFRow rows = sheet.createRow(i + 2);
rows.createCell(0).setCellValue(DateUtil.formatDateTime(list.get(i).getResultDateTime()));
rows.createCell(1).setCellValue(list.get(i).getReportItemName());
rows.createCell(2).setCellValue(list.get(i).getResult());
rows.createCell(3).setCellValue(list.get(i).getUnits());
rows.createCell(4).setCellValue(list.get(i).getNormalIndicator());
rows.createCell(5).setCellValue(list.get(i).getReferenceRange());
}
try {
String fileName = new String((master.getItemName() + ".xls").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");
OutputStream os = response.getOutputStream();
wb.write(os);
os.flush();
os.close();
} catch (Exception var8) {
throw new ServiceException("導出excel發生異常", var8);
}
}