导入的jar
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.8</version>
</dependency>
代码块
public static void CreateExcel(String path, List<Map<String, Object>> mapList) throws Exception{
//创建Excel文件薄
HSSFWorkbook workbook=new HSSFWorkbook();
//创建工作表sheeet
HSSFSheet sheet=workbook.createSheet();
sheet.setDefaultRowHeight( ( short )(20*20) );
if(mapList==null||mapList.size()==0){
return;
}
Map<String, Object> obj=mapList.get(0);
List<String> strings1=new ArrayList<>();
obj.forEach((k,v)->{
strings1.add(k);
});
//获取一个基本的带边框的单元格
HSSFCellStyle cellStyle= getBasicCellStyle(workbook);
HSSFRow row=sheet.createRow(0);
for (int i = 0; i < strings1.size(); i++) {
//设置每列的宽度
sheet.setColumnWidth(i,220*20);
String head=strings1.get(i);
//创建第一行
HSSFCell cell2=row.createCell(i);
//设置值及样式
cell2.setCellStyle(cellStyle);
cell2.setCellType(HSSFCell.CELL_TYPE_STRING);
cell2.setCellValue(head);
}
CellStyle style =getBasicCellStyle(workbook);
style.setFillForegroundColor(IndexedColors.CORNFLOWER_BLUE.getIndex());
style.setFillPattern(CellStyle.SOLID_FOREGROUND);
//追加数据
for (int i=0 ; i< mapList.size() ; i++){
HSSFRow nextrow=sheet.createRow(i+1);
Map<String, Object> obj2=mapList.get(i);
for (int j = 0; j < strings1.size(); j++) {
String key=strings1.get(j);
Object val=obj2.get(key);
HSSFCell cell2=nextrow.createCell(j);
//设置值及样式
cell2.setCellStyle(style);
cell2.setCellType(HSSFCell.CELL_TYPE_STRING);
cell2.setCellValue(String.valueOf(val));
}
}
//创建一个文件
File file=new File(path);
file.createNewFile();
FileOutputStream stream= FileUtils.openOutputStream(file);
workbook.write(stream);
stream.close();
}
/**
* 获取一个基本的带边框的单元格
* @param workbook
* @return
*/
private static HSSFCellStyle getBasicCellStyle(HSSFWorkbook workbook){
HSSFCellStyle hssfcellstyle = workbook.createCellStyle();
hssfcellstyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
hssfcellstyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
hssfcellstyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
hssfcellstyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
hssfcellstyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
hssfcellstyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
hssfcellstyle.setWrapText(true);
return hssfcellstyle;
}
/**
* 获取带有背景色的标题单元格
* @param workbook
* @return
*/
private static HSSFCellStyle getTitleCellStyle(HSSFWorkbook workbook){
HSSFCellStyle hssfcellstyle = getBasicCellStyle(workbook);
hssfcellstyle.setFillForegroundColor((short) HSSFColor.CORNFLOWER_BLUE.index); // 设置背景色
hssfcellstyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
return hssfcellstyle;
}