依赖
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
方法
private File createReport(List<BillForReport> billList,String fileName){
File file = null;
try {
file = File.createTempFile(fileName, ".tmp"); //临时文件
}catch (Exception e){
e.printStackTrace();
return null;
}
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("BillReport");
HSSFRow rowhead = sheet.createRow((short)0);
rowhead.createCell(0).setCellValue("流水号");
rowhead.createCell(1).setCellValue("订单编号");
rowhead.createCell(2).setCellValue("商品名称");
rowhead.createCell(3).setCellValue("付款用户Id");
rowhead.createCell(4).setCellValue("经办人");
rowhead.createCell(5).setCellValue("交易金额");
rowhead.createCell(6).setCellValue("交易方式");
for(int i=0;i<billList.size();i++) {
HSSFRow row = sheet.createRow((short) (i+1));
BillForReport bill = billList.get(i);
row.createCell(0).setCellValue(bill.getSerialNumber());
row.createCell(1).setCellValue(bill.getOrderNumber());
row.createCell(2).setCellValue(bill.getProductName());
row.createCell(3).setCellValue(bill.getPaymentUserId());
row.createCell(4).setCellValue(bill.getHandler());
row.createCell(5).setCellValue(bill.getTransactionAmount());
}
//auto column width 自适应列宽
HSSFRow row = workbook.getSheetAt(0).getRow(0);
for(int colNum=0;colNum<row.getLastCellNum();colNum++){
workbook.getSheetAt(0).autoSizeColumn(colNum);
}
try {
FileOutputStream fileOut = new FileOutputStream(file);
workbook.write(fileOut);
fileOut.close();
workbook.close();
}catch(Exception e){
e.printStackTrace();
}
return file;
}
Service中调用,传参中需要HttpServletResponse response
File reportFile = createReport(resultBills, filename);
if (reportFile != null) {
try {
response.setContentType("multipart/form-data; boundary=something");
response.setCharacterEncoding("UTF-8");
response.setHeader("Content-Disposition", "attachment;fileName=" + filename);
response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
System.out.println(reportFile.getAbsoluteFile());
OutputStream os = response.getOutputStream();
IOUtils.copy(new BufferedInputStream(new FileInputStream(reportFile)), os);
os.close();
} catch (IOException e) {
e.printStackTrace();
return new ErrorBaseResponse(false, 1069, "Error download report");
}
return new CommonBaseResponse<String>(true, null, "download report successfully ");
} else {
return new ErrorBaseResponse(false, 1069, "Error download report");
}