Skip to content

Instantly share code, notes, and snippets.

@ostholz
Created May 8, 2013 08:57
Show Gist options
  • Save ostholz/5539196 to your computer and use it in GitHub Desktop.
Save ostholz/5539196 to your computer and use it in GitHub Desktop.
Apache POI Generate xls
public void exportToExcel(Window mainWindow){
//String title;
// String[] Headers TableColumnsDef. , Data, outputStream
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Export");
// Header Style
HSSFCellStyle style = workbook.createCellStyle();
style.setFillForegroundColor(HSSFColor.SKY_BLUE.index);
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
HSSFFont font = workbook.createFont();
font.setColor(HSSFColor.VIOLET.index);
font.setFontHeightInPoints((short) 12);
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
style.setFont(font);
// Body Style
HSSFCellStyle style2 = workbook.createCellStyle();
// style2.setFillForegroundColor(HSSFColor.LIGHT_YELLOW.index);
style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style2.setBorderRight(HSSFCellStyle.BORDER_THIN);
style2.setBorderTop(HSSFCellStyle.BORDER_THIN);
style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);
style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
HSSFFont font2 = workbook.createFont();
font.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
style2.setFont(font2);
// Create Title Row
HSSFRow row = sheet.createRow(0);
for (int i=0; i< TableColumnsDef.PSI_COLS_NAME.length; i++){
HSSFCell cell = row.createCell(i);
cell.setCellStyle(style);
HSSFRichTextString text = new HSSFRichTextString(TableColumnsDef.PSI_COLS_NAME[i]);
cell.setCellValue(text);
}
// Create Body
SQLContainer container = DatabaseUtil.getInstance().getPsiContainer();
for (int i=0; i<container.size(); i++){
Object id = container.getIdByIndex(i);
Item item = container.getItem(id);
row = sheet.createRow(i+1);
for (int j=0; j<TableColumnsDef.PSI_COLS_ORDER.length; j++){
HSSFCell cell = row.createCell(j);
HSSFRichTextString text = new HSSFRichTextString(item.getItemProperty(TableColumnsDef.PSI_COLS_ORDER[j]).toString());
cell.setCellValue(text);
}
}
// download
File tempFile = null;
FileOutputStream fileOut = null;
try {
tempFile = File.createTempFile("tmp", ".xls");
fileOut = new FileOutputStream(tempFile);
workbook.write(fileOut);
mainWindow.open(new FileResource(tempFile, mainWindow.getApplication()));
} catch (IOException e){
System.out.println("failed with IOException");
} finally {
tempFile.deleteOnExit();
try {
fileOut.close();
} catch (IOException e){
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment