packagecom.royan.weakey.platform.common.excel;importcom.google.common.collect.Lists;importcom.sun.xml.internal.ws.api.streaming.XMLStreamReaderFactory;importlombok.extern.slf4j.Slf4j;importorg.apache.poi.hssf.usermodel.HSSFWorkbook;importorg.apache.poi.ss.usermodel.Cell;importorg.apache.poi.ss.usermodel.Row;importorg.apache.poi.ss.usermodel.Sheet;importorg.apache.poi.ss.usermodel.Workbook;importorg.apache.poi.xssf.usermodel.XSSFWorkbook;import java.io.*;import java.util.*;/*** writeExcel*/@Slf4jpublic classWriteExcel {private static final String EXEL_XLS = "xls";private static final String EXEL_XLSX = "xlsx";public static void writeExcel(List dataList, String filePath, Listheader) {
OutputStream out= null;try{/**read excel document*/File file= newFile(filePath);
Workbook workbook= null;if(file.isDirectory()) {//default create .xls
workbook = newHSSFWorkbook();
}else if (file.getName().endsWith(".xls")) {
workbook= newHSSFWorkbook();
}else if (file.getName().endsWith(".xlsx")) {
workbook= newXSSFWorkbook();
}else
throw new Exception("please get .xls .xlsx end or directory,[" + filePath + "]");//if only support single sheet
Sheet sheet = workbook.createSheet("data");//set excel header
Row fisrtRow = sheet.createRow(0);int columnCount =header.size();for (int h = 0; h < columnCount; h++) {
fisrtRow.createCell(h).setCellValue(header.get(h));
}/*** fill up data in excel*/
int i = 1;for(Map data : dataList) {
Row row=sheet.createRow(i);
Object[] arrays=data.values().toArray();for (int j = 0; j < columnCount; j++) {
Object obj=arrays[j];
row.createCell(j).setCellValue(obj!= null ? obj.toString() : "");
}
i++;
}
out= new FileOutputStream(file.isDirectory() ? filePath + "/" + header.get(0) + ".xls": filePath);
workbook.write(out);
}catch(Exception e) {
log.info("exception {}", e);
}finally{try{if (out != null) {
out.flush();
out.close();
}
}catch(IOException o) {
log.info("exception {}", o);
}
log.info("data output success");
}
}public static voidmain(String[] args) {
Map dataMap = new HashMap<>();
dataMap.put("BankName", "BankName");
dataMap.put("Addr", "Addr");
dataMap.put("Phone", "Phone");
Map dataMap1 = new HashMap<>();
dataMap1.put("BankName", "BankName1");
dataMap1.put("Addr", "Addr1");
dataMap1.put("Phone", "Phone1");
List header = new LinkedList<>();
header.add("BankName");
header.add("Addr");
header.add("Phone");
List list = new ArrayList<>();
list.add(dataMap);
list.add(dataMap1);
writeExcel(list,"/Users/caibixiang/workSoftware/log", header);
}
}