Monday, September 26, 2005

Using POI to create Excel file in Java

I try to use Apache's POI to create an Excel file. It works well and really simple code.

Here is step by step to create an Excel file by POI:

- Create a output stream to generate Excel file: FileOutputStream outStream = new FileOutputStream("test.xls");
- Create a workbook: HSSFWorkbook workbook = new HSSFWorkbook();
- Create a worksheet: HSSFSheet sheet = workbook.createSheet("Result sheet");
- Create a row: HSSFRow row = sheet.createRow(index);
- Create a cell and set its value on a row: row.createCell(index).setCellValue(value);
- Generate Excel file: workbook.write(outStream);
- And clean up: outStream.close();

Note: index of cell must be in short type.

And I also found another API to create Excel file in Java, JExcelApi. It's also free (it is issued on under the GNU Lesser General Public License) as Apache's POI.

No comments: