1、response设置文件类型和header
//
- HSSFWorkbook(处理97(-2007) 的.xls)
- XSSFWorkbook(处理2007 OOXML (.xlsx) )
response.setHeader("Content-Disposition", "attachment; filename=" + newFilename); response.setContentType("application/vnd.ms-excel; charset=utf-8"); try (OutputStream output = response.getOutputStream()) { LazadaCancelOrderItemUtils.exportExcel(output, lazadaCancelOrderItems, domain); }
2、写文件
// 建立新HSSFWorkbook对象 这里使用 try(){}==>try块退出时,会自动调用res.close()方法,关闭资源。 try (XSSFWorkbook wb = new XSSFWorkbook()) { // 建立新的XSSFSheet对象 XSSFSheet sheet = wb.createSheet(); XSSFRow titleRow = sheet.createRow(0); XSSFCell cell = null; // 表头字段列表 String[] titles = new String[]{"归属部门", "卖家账号", "平台站点", "平台订单号", "产品标识", "产品SKU", "明细状态", "售出时间"}; // 写表头 for (int i = 0; i < titles.length; i++) { cell = titleRow.createCell(i); cell.setCellValue(titles[i]); } int rowNum = 1; SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // 表数据 for (LazadaCancelOrderItem item : lazadaCancelOrderItems) { int cellNum = 0; XSSFRow row = sheet.createRow(rowNum++); // 归属部门 cell = row.createCell(cellNum++); Integer deptId = item.getDeptId(); if (deptId != null) { Department department = DepartmentUtils.getDepartment(deptId); if (department != null) { cell.setCellValue(department.getDepartmentName()); } } // 卖家账号 cell = row.createCell(cellNum++); cell.setCellValue(item.getAccount()); // 平台站点 cell = row.createCell(cellNum++); LazadaSiteEnum build = LazadaSiteEnum.build(item.getSite()); String site = build != null ? build.display() : item.getSite(); cell.setCellValue(site); // 平台订单号 cell = row.createCell(cellNum++); cell.setCellValue(item.getPlatformOrderId()); // 产品标识 cell = row.createCell(cellNum++); cell.setCellValue(item.getProductId()); // 产品SKU cell = row.createCell(cellNum++); cell.setCellValue(item.getSku()); // 明细状态 cell = row.createCell(cellNum++); cell.setCellValue(item.getStatus()); // 售出时间 cell = row.createCell(cellNum); cell.setCellValue(dateFormat.format(item.getSaleTime())); } // 写入Excel wb.write(output); }