How to Export JTable data into Excel Sheet?
Some times it is required to generate report based on the data in the JTable. In that case the POI-HSSF API to access Microsoft Excel document is very much useful to generate Excel file using the content of JTable.
Let's see below how to use this API to generate Excel file.
As a first step download the API from here.
Place the poi jar files into the your classpath.
First create a workbook like this.
HSSFWorkbook wb = new HSSFWorkbook();
Then create worksheet with the following method.
HSSFSheet sheet = wb.createSheet(sheetNames);
The work sheet can be decorated with different font properties as follows.HSSFFont sheetTitleFont = wb.createFont();
sheetTitleFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
HSSFCellStyle sheetTitleFontCellStyle = wb.createCellStyle();
sheetTitleFontCellStyle.setFont(sheetTitleFont);
HSSFRow sheetTitleRow = sheet.createRow( (short) row);
HSSFCell cell = sheetTitleRow.createCell( (short) 0);
The following method will set the value to the cell in the excel sheet.
cell.setCellValue(tableTitle);
cell.setCellStyle(sheetTitleFontCellStyle);
try {
provide some file path in this method
FileOutputStream fos = new FileOutputStream(xlsFilePath);
BufferedOutputStream bos = new BufferedOutputStream(fos);
write the work book content into the xls file
wb.write(bos);
bos.close();
fos.close();
return true;
} catch (Exception e) {
return false;
}
} catch (Exception e) {
e.printStackTrace();
0 comments:
Post a Comment