最近的项目中遇到需要将List<Map<String,String>>存储到Excel文件中,为满足此需求设计实现了如下函数:
1 /** 2 * 将MapList转化为Excel文件 3 * @param excelFile--excel文件的路径 4 * @param mapList---要存储的mapList 5 * @param titles----对应的列名称 6 * @param enTitles---列名称map的keys数组 7 * @throws Exception 8 */ 9 public void mapListToExcel(String excelFile,List<Map<String, String>> mapList, Map<String, String> titles, String[] enTitles) throws Exception{ 10 FileOutputStream fos=new FileOutputStream(excelFile); 11 HSSFWorkbook workbook = new HSSFWorkbook(); 12 HSSFCellStyle style = workbook.createCellStyle(); 13 List<HSSFSheet> sheets = new ArrayList<HSSFSheet>(); 14 /** 15 * 设置其它数据风格 16 */ 17 style.setBorderBottom(HSSFCellStyle.BORDER_THIN); // 设置单无格的边框为粗体 18 style.setBottomBorderColor(HSSFColor.BLACK.index); // 设置单元格的边框颜色. 19 style.setBorderLeft(HSSFCellStyle.BORDER_THIN); 20 style.setLeftBorderColor(HSSFColor.BLACK.index); 21 style.setBorderRight(HSSFCellStyle.BORDER_THIN); 22 style.setRightBorderColor(HSSFColor.BLACK.index); 23 style.setBorderTop(HSSFCellStyle.BORDER_THIN); 24 style.setTopBorderColor(HSSFColor.BLACK.index); 25 style.setWrapText(true);//自动换行 26 27 int columnNum = 0; //列数 28 int rowNum = 0; //行数 29 int sheetNum = 0; //工作簿数 30 31 if(mapList == null || mapList.size() == 0) 32 { 33 sheets.add(createSheet(workbook,titles,style,"sheet" + sheetNum,enTitles)); 34 return ; 35 } 36 37 Iterator<Map<String, String>> iter = mapList.iterator(); 38 39 while(iter.hasNext()) 40 { 41 Map<String, String> obj = iter.next(); 42 if(rowNum == 0) 43 { 44 sheets.add(createSheet(workbook,titles,style,"sheet" + sheetNum,enTitles)); 45 sheetNum++; 46 } 47 rowNum++; 48 columnNum = 0; 49 HSSFRow dataRow = sheets.get(sheetNum-1).createRow(rowNum); 50 51 52 for(String title: enTitles){ 53 HSSFCell cell = dataRow.createCell(columnNum); 54 String value = obj.get(title); 55 cell.setCellValue(value); 56 cell.setCellStyle(style); 57 columnNum++; 58 } 59 60 if(rowNum > 65534) 61 { 62 rowNum = 0; 63 } 64 } 65 66 workbook.write(fos); 67 fos.close(); 68 69 70 } 71 72 /** 73 创建Excel工作簿 74 */ 75 private HSSFSheet createSheet(HSSFWorkbook workbook,Map<String, String> titles,HSSFCellStyle style,String sheetname, String[] enTitles) 76 { 77 HSSFSheet sheet = workbook.createSheet(sheetname); 78 sheet.autoSizeColumn(1, true); //列自适应宽度 79 int columnNum = 0; 80 int rowNum = 0; 81 HSSFRow titleRow = sheet.createRow(rowNum); 82 83 for(String key: enTitles){ 84 HSSFCell cell = titleRow.createCell(columnNum); 85 String title = titles.get(key); 86 cell.setCellValue(title); 87 cell.setCellStyle(style); 88 columnNum++; 89 } 90 return sheet; 91 }