poi excel download
1. Declare the browser type: application/vnd.ms-excel
public static final String XLS = "application/vnd.ms-excel";
//create EXCEL HSSFWorkbook wb = new HSSFWorkbook(); HSSFSheet sheet = wb.createSheet("Leave Statistics"); HSSFRow row = sheet.createRow((int) 0); HSSFCellStyle style = wb.createCellStyle(); style.setAlignment(HSSFCellStyle.ALIGN_CENTER); //Create Excel header file int i = 0; for(Map.Entry<String, String> entry : exportExcelFields().entrySet()){ HSSFCell cell = row.createCell(i); String value = entry.getValue(); System.out.println("value====="+value); cell.setCellValue(value); cell.setCellStyle(style); sheet.autoSizeColumn(i); sheet.setColumnWidth(i, 5000); i++; } //create data if(null!=users && users.size()>0){ i=1; for(User user : users){ Map<String,Object> map = (Map<String,Object>) JSONObject.fromObject(user); row = sheet.createRow(i); int j = 0; for(Map.Entry<String, String> entry : exportExcelFields().entrySet()){ String key = entry.getKey(); String value = map.get(key)==null?"":String.valueOf(map.get(key)); System.out.println("key=========="+key+" value====="+value); if("sex".equals(key)) row.createCell(j).setCellValue("F".equals(value.toUpperCase())?'女' : '男'); else row.createCell(j).setCellValue(value); sheet.autoSizeColumn (j); j++; } i++; } } this.writeExcel(response, wb, "leave statistics.xls");
3. The response to the client has been streamed
public static void writeExcel(HttpServletResponse response, HSSFWorkbook workbook, String filename) throws IOException {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
workbook.write(byteArrayOutputStream);
byte[] bytes = byteArrayOutputStream.toByteArray();
// clear the response
response.reset();
// Set the Header of the response
response.setContentType(XLS+";charset=utf-8");
response.addHeader("Content-Disposition", "attachment;filename=" + new String (filename.getBytes("utf-8"),"iso8859-1"));
response.addHeader("Content-Length", "" + bytes.length);
OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
outputStream.write(bytes);
outputStream.flush();
outputStream.close();
}