Thursday, March 5, 2009

Java : Simple java program to write an Excel File using Apache POI

This is a simple java code to create Excel File, you can customize according to user need.. you can write multiple Excel file with multiple excel Sheet, write desire data etc

Note : to run this code u need to download POI

/* Here is the code for WriteExcel .java */

import java.util.*;

import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFRow;

public class WriteExcel
public static void main(String[] args) throws IOException

String excelFileName = "myExcelFile.xls";//name of excel file

String sheetName = "Sheet1";//name of sheet

HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet(sheetName) ;

//creating Random numbers
//Random is a inbuilt java class in 1.5 in util package
Random random = new Random();

//iterating r number of rows
for (int r=0;r < 10; r++ )
HSSFRow row = sheet.createRow(r);

//iterating c number of columns
for (int c=0;c < 5; c++ )
HSSFCell cell = row.createCell((short)c);
//createCell(short) method is Deprecated
//you can use createCell(int) method also

int temp = random.nextInt(100);//get random int values between 0 and 100

cell.setCellValue(temp);//write temp values

//You can also provide path where to save this excel file
FileOutputStream fileOut = new FileOutputStream(excelFileName);

wb.write(fileOut);//write out this workbook to an Outputstream.

1 comment:

  1. it Showing following Errors:Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/poi/hssf/u
    at WriteExcelDemo.main(
    Caused by: java.lang.ClassNotFoundException: org.apache.poi.hssf.usermodel.HSSFW
    at Method)
    at java.lang.ClassLoader.loadClass(
    at sun.misc.Launcher$AppClassLoader.loadClass(
    at java.lang.ClassLoader.loadClass(
    ... 1 more