Table of Contents [hide]
Some basics about Apache POI:
There are two prefixes which you encounter while reading/writing excel in java
HSSF: Used for dealing with files excel 2003 or earlier(.xls). Some of classes with HSSF prefix are HSSFWorkbook , HSSFSheet , HSSFRow and HSSFCell.
XSSF: Used for dealing with files excel 2007 or later(.xlsx). Some of classes with XSSF prefix are XSSFWorkbook , XSSFSheet , XSSFRow and XSSFCell.
Here are few classes which you need to aware of.
- Workbook : This is high level class for representing excel workbook.
- Sheet : This is high level class for representing excel sheet.
- Row : This is high level class for representing excel row. It has methods which are related to row.
- Cell: This is high level class for representing individual excel cell. It has methods which are related to cell for example : getDataType().
Dependency:
- poi-3.13.jar
- commons-codec-1.9.jar
- poi-ooxml-3.13.jar
- poi-ooxml-schemas-3.13.jar
- xmlbeans-2.6.0.jar
- stax-api-1.0.1.jar
write excel file using poi:
- Create a blank workbook
- Create a sheet and pass name of the sheet
- Create row
- Create cells, set its value and add cell to above row
- Repeat 3 and 4 until you have data
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet(“Country”);
Row row = sheet.createRow(rownum++);
Cell cell = row.createCell(cellnum++); if(obj instanceof String) cell.setCellValue((String)obj); else if(obj instanceof Double) cell.setCellValue((Double)obj); else if(obj instanceof Integer) cell.setCellValue((Integer)obj);
Java Program:
We are going to write excel file named “CountriesDetails.xlsx” Create WriteExcelMain.java as below
When you run above program, you will get following output:
Lets see content of CountriesDetails.xlsx now.

Good example