l创建Excel文件

最近的项目中遇到需要将List<Map<String,String>>存储到Excel文件中,为满足此需求设计实现了如下函数:

     /**
* 将MapList转化为Excel文件
* @param excelFile--excel文件的路径
* @param mapList---要存储的mapList
* @param titles----对应的列名称
* @param enTitles---列名称map的keys数组
* @throws Exception
*/
public void mapListToExcel(String excelFile,List<Map<String, String>> mapList, Map<String, String> titles, String[] enTitles) throws Exception{
FileOutputStream fos=new FileOutputStream(excelFile);
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFCellStyle style = workbook.createCellStyle();
List<HSSFSheet> sheets = new ArrayList<HSSFSheet>();
/**
* 设置其它数据风格
*/
style.setBorderBottom(HSSFCellStyle.BORDER_THIN); // 设置单无格的边框为粗体
style.setBottomBorderColor(HSSFColor.BLACK.index); // 设置单元格的边框颜色.
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style.setLeftBorderColor(HSSFColor.BLACK.index);
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
style.setRightBorderColor(HSSFColor.BLACK.index);
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
style.setTopBorderColor(HSSFColor.BLACK.index);
style.setWrapText(true);//自动换行 int columnNum = 0; //列数
int rowNum = 0; //行数
int sheetNum = 0; //工作簿数 if(mapList == null || mapList.size() == 0)
{
sheets.add(createSheet(workbook,titles,style,"sheet" + sheetNum,enTitles));
return ;
} Iterator<Map<String, String>> iter = mapList.iterator(); while(iter.hasNext())
{
Map<String, String> obj = iter.next();
if(rowNum == 0)
{
sheets.add(createSheet(workbook,titles,style,"sheet" + sheetNum,enTitles));
sheetNum++;
}
rowNum++;
columnNum = 0;
HSSFRow dataRow = sheets.get(sheetNum-1).createRow(rowNum); for(String title: enTitles){
HSSFCell cell = dataRow.createCell(columnNum);
String value = obj.get(title);
cell.setCellValue(value);
cell.setCellStyle(style);
columnNum++;
} if(rowNum > 65534)
{
rowNum = 0;
}
} workbook.write(fos);
fos.close(); } /**
创建Excel工作簿
*/
private HSSFSheet createSheet(HSSFWorkbook workbook,Map<String, String> titles,HSSFCellStyle style,String sheetname, String[] enTitles)
{
HSSFSheet sheet = workbook.createSheet(sheetname);
sheet.autoSizeColumn(1, true); //列自适应宽度
int columnNum = 0;
int rowNum = 0;
HSSFRow titleRow = sheet.createRow(rowNum); for(String key: enTitles){
HSSFCell cell = titleRow.createCell(columnNum);
String title = titles.get(key);
cell.setCellValue(title);
cell.setCellStyle(style);
columnNum++;
}
return sheet;
}
上一篇:Java和Flex整合报错(五)


下一篇:一文学会最常见的10种NLP处理技术