Create an Excel(.xlsx) file using POI

Here I am giving a very basic example for creating a basic .xlsx file using poi.jar. This code will create a .xlsx file in a certain location & write some text in it. But we need to use a number of jars for that.
They are -

i) dom4j-1.5.1.jar
ii) ooxml-schemas-1.0.jar
iii) poi-3.5-FINAL.jar
iv) poi-ooxml-3.5-FINAL.jar
v) xmlbeans-2.3.0.jar










Now, here goes the code -

 
package com.test.poi;

import java.io.File;
import java.io.FileOutputStream;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class WriteInExcel {

 public static void main(String[] args) {

  XSSFWorkbook excelWorkBook;
  excelWorkBook = new XSSFWorkbook();
  //Write Sheet Name
  XSSFSheet sheet = excelWorkBook.createSheet("Sheet1");

  //enter some data in the Excel
  XSSFRow labelRow = sheet.createRow(0);
  XSSFCell versionLabel = labelRow.createCell(0);
  versionLabel.setCellValue("TEST1");
  XSSFCell filePathLabel = labelRow.createCell(1);
  filePathLabel.setCellValue("TEST2");
  
  try {
   FileOutputStream out = new FileOutputStream(new File(
     "D:\\SampleExcelWorkbook.xlsx")); // file location
   excelWorkBook.write(out);
   out.close();
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
}


This will create a .xlsx file in D: drive & create a sheet named "Sheet1" & write "TEST1" in first row first column & "TEST2" in first row second column.

Happy Learning !!

No comments :

Post a Comment