Write to an MS Excel File using Apache POI
Overview
This tutorial outlines the steps to create an MS Excel File using Apache POI. We can create an object of Workbook using the following statement:
Workbook wb = new XSSFWorkbook();
Create a new sheet in the Workbook using the statement. Sample Sheet is the sheet name:
Sheet sheet = wb.createSheet(“Sample Sheet”);
To create a Row, we can use the following statement. We need to pass the row index, which starts with 0.
Row row = sheet.createRow(0);
Create a cell. The cell index also starts with 0. The first cell in the Excel sheet is identified by row 0, cell 0.
Cell cell=row.createCell(0);
To write to the cell:
cell.setCellValue(“Sample Data”);
Sample Code
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.WorkbookFactory; import org.apache.poi.xssf.usermodel.XSSFWorkbook; /********************************************* * Sample Java Program to create Excel file * with Sample Data. * * www.TestingDocs.com - Apache POI Tutorials * *********************************************/ public class WriteExcel { public static void main(String[] args) throws InvalidFormatException, IOException{ String fileName = "TDocs.xlsx"; Workbook wb = new XSSFWorkbook(); Sheet sheet = wb.createSheet("Sample Sheet"); Row row = sheet.createRow(0); Cell cell=row.createCell(0); cell.setCellValue("www.TestingDocs.com"); FileOutputStream fos=new FileOutputStream(fileName); wb.write(fos); fos.close(); System.out.println("Check the File in the Project Root."); }}
Construct FileOutputStream stream object. We can pass the filename or file path to the constructor.
The write() method writes the contents to the Excel file. Once done we can invoke the close() method to release the file resources.
Sample Output
That’s it. This is a basic example of writing to an Excel file using the Apache POI API in a Java program.
—
Apache POI Tutorials:
https://www.testingdocs.com/apache-poi-tutorials/
More Information on Apache POI API: