Thursday, November 15, 2012

POI API to Write Data into Excel Sheet


import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;

public class PoiWriteExcelFile {

public static void main(String[] args) {
try {
FileOutputStream fileOut = new FileOutputStream("poi-test.xls");
HSSFWorkbook workbook = new HSSFWorkbook();
//creating sheets in excel
HSSFSheet worksheet = workbook.createSheet("POI Worksheet1");
HSSFSheet worksheet2 = workbook.createSheet("Worksheet2");

//adding a row to sheet
HSSFRow row1 = worksheet.createRow(0);

HSSFCell cellA1 = row1.createCell(0);
cellA1.setCellValue("Hello");
/*HSSFCellStyle cellStyle = workbook.createCellStyle();
cellStyle.setFillForegroundColor(HSSFColor.GOLD.index);
cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
cellA1.setCellStyle(cellStyle);*/

HSSFCell cellB1 = row1.createCell(1);
cellB1.setCellValue("Goodbye");
/*cellStyle = workbook.createCellStyle();
cellStyle.setFillForegroundColor(HSSFColor.LIGHT_CORNFLOWER_BLUE.index);
cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
cellB1.setCellStyle(cellStyle);*/

HSSFCell cellC1 = row1.createCell(2);
cellC1.setCellValue(true);

HSSFCell cellD1 = row1.createCell(3);
cellD1.setCellValue(new Date());
/*cellStyle = workbook.createCellStyle();
cellStyle.setDataFormat(HSSFDataFormat
.getBuiltinFormat("m/d/yy h:mm"));
cellD1.setCellStyle(cellStyle);*/


HSSFRow s2row1 = worksheet2.createRow(0);
HSSFCell s2cellA1 = s2row1.createCell(0);
s2cellA1.setCellValue("Hello");
HSSFCell s2cellA2 = s2row1.createCell(1);
s2cellA2.setCellValue("secondcell");
workbook.write(fileOut);
fileOut.flush();
fileOut.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

}

}
jars required for this Program are ,



No comments:

Post a Comment