Java Gen Excel ด้วย POI ขอตัวอย่าง ง่ายๆ ครับ
Apache POI ถือว่าเป็น Library ที่ใช้ในการ Read , Write Excel ด้วย ภาษา Java
ที่นิยมใช้กันมากที่สุด
ตัวอย่างง่ายๆ สำหรับการ Write file
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Sample sheet");
Map
data.put("1", new Object[] {"Code ID", "Emp Name", "Salary","Birth day"});
data.put("2", new Object[] {1d, "Somchai", 25000d,new Date()});
data.put("3", new Object[] {2d, "Samsanv", 30000d,new Date()});
data.put("4", new Object[] {3d, "Looktao", 53000d,new Date()});
CreationHelper createHelper = workbook.getCreationHelper();
HSSFFont font = workbook.createFont();
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
font.setFontHeightInPoints((short)24);
font.setFontName("Courier New");
font.setItalic(true);
font.setStrikeout(true);
HSSFCellStyle hstyle = workbook.createCellStyle();
hstyle.setFont(font);
hstyle.setAlignment(CellStyle.ALIGN_CENTER);
hstyle.setBorderBottom(CellStyle.BORDER_THIN);
hstyle.setBottomBorderColor(IndexedColors.BLACK.getIndex());
hstyle.setBorderLeft(CellStyle.BORDER_THIN);
hstyle.setLeftBorderColor(IndexedColors.GREEN.getIndex());
hstyle.setBorderRight(CellStyle.BORDER_THIN);
hstyle.setRightBorderColor(IndexedColors.BLUE.getIndex());
hstyle.setBorderTop(CellStyle.BORDER_MEDIUM_DASHED);
hstyle.setTopBorderColor(IndexedColors.BLACK.getIndex());
hstyle.setFillForegroundColor(IndexedColors.ORANGE.getIndex());
hstyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
Set
int rownum = 0;
for (String key : keyset) {
Row row = sheet.createRow(rownum++);
Object [] objArr = data.get(key);
int cellnum = 0;
for (Object obj : objArr) {
Cell cell = row.createCell(cellnum++);
if(rownum==1){
cell.setCellStyle(hstyle);
}
if(obj instanceof Date){
cell.setCellValue((Date)obj);
CellStyle cellStyle = workbook.createCellStyle();
cellStyle.setDataFormat(createHelper.createDataFormat().getFormat("m/d/yy h:mm"));
cell.setCellStyle(cellStyle);
} else if(obj instanceof Boolean)
cell.setCellValue((Boolean)obj);
else if(obj instanceof String)
cell.setCellValue((String)obj);
else if(obj instanceof Double)
cell.setCellValue((Double)obj);
}
}
try {
FileOutputStream out =
new FileOutputStream(new File("C:\\new.xls"));
workbook.write(out);
out.close();
System.out.println("Excel written successfully..");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}