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表並導出到本地