package com.ibeetl.admin.core.util.fileexport; import lombok.Data; import org.apache.poi.hssf.usermodel.*; import org.apache.poi.hssf.util.HSSFColor; import org.apache.poi.ss.usermodel.*; import javax.servlet.http.HttpServletResponse; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.List; import java.util.Map; import java.util.UUID; @Data public class FileExportUtil { /** * @功能:手工构建一个简单格式的Excel */ public static HSSFWorkbook createExcel(Map> map, String[] strArray, String path) { // 第一步,创建一个webbook,对应一个Excel文件 HSSFWorkbook wb = new HSSFWorkbook(); // 第二步,在webbook中添加一个sheet,对应Excel文件中的sheet HSSFSheet sheet = wb.createSheet("sheet1"); sheet.setDefaultColumnWidth(20);// 默认列宽 // 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short HSSFRow row = sheet.createRow((int) 0); // 第四步,创建单元格,并设置值表头 设置表头居中 HSSFCellStyle style = wb.createCellStyle(); // 创建一个居中格式 // 添加excel title HSSFCell cell = null; for (int i = 0; i < strArray.length; i++) { cell = row.createCell((short) i); cell.setCellValue(strArray[i]); cell.setCellStyle(style); } // 第五步,写入实体数据 实际应用中这些数据从数据库得到,list中字符串的顺序必须和数组strArray中的顺序一致 int i = 0; for (String str : map.keySet()) { row = sheet.createRow((int) i + 1); List list = map.get(str); // 第四步,创建单元格,并设置值 for (int j = 0; j < strArray.length; j++) { row.createCell((short) j).setCellValue(list.get(j)); } // 第六步,将文件存到指定位置 /*try { FileOutputStream fout = new FileOutputStream(path+".xls"); wb.write(fout); fout.close(); } catch (Exception e) { e.printStackTrace(); }*/ i++; } return wb; } public static void setResponseInfo(HttpServletResponse response, HSSFWorkbook wb, String name) throws IOException { //导出数据 try { //设置Http响应头告诉浏览器下载这个附件 response.setHeader("Content-Disposition", "attachment;Filename=" + name + ".xls"); OutputStream outputStream = response.getOutputStream(); wb.write(outputStream); outputStream.close(); } catch (Exception ex) { ex.printStackTrace(); throw new IOException("导出Excel出现严重异常,异常信息:" + ex.getMessage()); } } }