package com.charm.busi.util; import java.io.ByteArrayOutputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletResponse; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.HorizontalAlignment; public class ExcelUtil { /** * @Description excel导出(自定义名称) * @author dangwangzhen * @param res * @param map * @param titleArray 标题头字符串数组 * @param fileName */ public static void exportExcel(HttpServletResponse res, Map<String, List<String>> map, String[] titleArray, String fileName) { // 第一步,创建一个webbook,对应一个Excel文件 HSSFWorkbook wb = new HSSFWorkbook(); // 第二步,在webbook中添加一个sheet,对应Excel文件中的sheet HSSFSheet sheet = wb.createSheet(fileName); sheet.setDefaultColumnWidth(30);// 默认列宽 // 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short HSSFRow row = sheet.createRow((int) 0); // 第四步,创建单元格,并设置值表头 设置表头居中 HSSFCellStyle style = wb.createCellStyle(); // 创建一个居中格式 style.setAlignment(HorizontalAlignment.CENTER); // 添加excel title HSSFCell cell = null; for (int i = 0; i < titleArray.length; i++) { cell = row.createCell((short) i); cell.setCellValue(titleArray[i]); cell.setCellStyle(style); } // 第五步,写入实体数据 实际应用中这些数据从数据库得到,list中字符串的顺序必须和数组strArray中的顺序一致 int i = 0; for (String str : map.keySet()) { row = sheet.createRow((int) i + 1); List<String> list = map.get(str); // 第四步,创建单元格,并设置值 for (int j = 0; j < titleArray.length; j++) { row.createCell((short) j).setCellValue(list.get(j)); } i++; } ByteArrayOutputStream fos = null; byte[] retArr = null; try { fos = new ByteArrayOutputStream(); wb.write(fos); retArr = fos.toByteArray(); } catch (IOException e) { e.printStackTrace(); } finally { try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } try { fileName = new String(fileName.getBytes(), "ISO-8859-1"); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } OutputStream os = null; try { os= res.getOutputStream(); res.reset(); res.setHeader("Content-Disposition", "attachment; filename="+fileName+".xls"); res.setContentType("application/octet-stream; charset=utf-8"); os.write(retArr); os.flush(); } catch (IOException e) { e.printStackTrace(); } finally { try { os.close(); } catch (IOException e) { e.printStackTrace(); } } } }
参考文章:
java实现创建excel表并导出到本地