Create Excel File in Java using Apache POI
Apache POI is a very useful library when it comes to reading/writing in Excel. POI stands for Poor Obfuscation Implementation, referring humorously to the fact that the file formats seemed to be deliberately obfuscated, but poorly, since they were successfully reverse-engineered. Ref
We will be using the latest version of POI libraries to create excel file.
Please go through the first part of the post Read Excel File in Java using Apache POI, which explain on how to set up the jars that we need to use.
Apache POI API
Workbook: is a high level representation of an Excel workbook. We have 2 implementations of the Workbook
HSSFWorkbook for xls files
XSSFWorkbook for xlsx files
workbook.createSheet() : creates a the sheet in the workbook.
Example : create .xls file using HSSFWorkbook
a. Create a FileOutStream instance with the location where we need to create the excel file
b. Create a HSSFWorkbook instance.
c. Using the HSSFWorkbook instance create a sheet using HSSFWorkbook.createSheet()
d. Now write the output stream into the workbook. This will create a excel file in the given location with the given file name.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | package com.kscodes.sampleproject; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; public class CreateExcelUsingPOI { public static void main(String[] args) { String excelFilePath = "C:\\kscodes\\testExcelFile.xls"; FileOutputStream xlsOutputStream = null; HSSFWorkbook workbook = null; try { xlsOutputStream = new FileOutputStream(new File(excelFilePath)); workbook = new HSSFWorkbook(); HSSFSheet sheet = workbook.createSheet("firstSheet"); workbook.write(xlsOutputStream); System.out .println("Excel File with name 'testExcelFile.xls' created with sheet name as 'firstSheet'"); } catch (Exception e) { System.out.println("Exception while reading Excel " + e); } finally { try { if (workbook != null) { workbook.close(); } if (xlsOutputStream != null) { xlsOutputStream.close(); } } catch (IOException e) { } } } } |