Tuesday 25 March 2014

Write data to Excel using Apache POI -Java

HI

This post is regarding writing data to a xlsx sheet.In java we had many powerful API's to write data to CSV or xlsx or xls files.One such API is apache POI by apache foundation.This API has classes and interfaces which helps us to write data to .csv or .xlsx sheets.

Here I am providing you a sample code snippet which helps you to explore and experiment more on this

ENVIRONMENT: java 1.6 sdk,apche poi  jars

Download location : http://poi.apache.org/download.html

Setup your environment add jars to the build path in eclipse.

Code begins:


 import java.io.FileOutputStream;

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.xssf.usermodel.XSSFWorkbook;

public class sample {

 public static void main(String[] args) {
   try {
  String sample="test content";
  Workbook wb=new XSSFWorkbook();
  Sheet sheet=wb.createSheet("samplesheet");
  Row row=sheet.createRow(0);
  Cell cell=row.createCell(0);
  row.getCell(0).setCellValue(sample);
  FileOutputStream fop=new FileOutputStream("sample.xlsx",true);
  wb.write(fop);
  fop.flush();
  fop.close();
  } catch (Exception e) {
  
   e.printStackTrace();
  }

 }

}   

Output: This sample created a Excel sheet with first cell filled with the string test content

No comments:

Post a Comment