How to write data in multiple cells in Excel using java? - java

I wrote a code for writing data in an Excel sheet.In this i have to write the data in multiple cells.But it is showing some Errors.For one cell it is able to change the data.I kept for loop for changing the data in multiple cells.For this it is showing Error.
Can any one tell me that where i did mistake.
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import java.lang.String;
import javax.swing.JOptionPane;
import jxl.Cell;
import org.apache.poi.hssf.util.CellReference;
import org.apache.poi.ss.formula.functions.Column;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFComment;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class Sele1
{
public static void main(String[] args)
{
// TODO Auto-generated method stub
String FileName = "C:\\Users\\u304081\\Desktop\\Java\\new.xlsx";
try
{
FileInputStream fileInputStream3 = new FileInputStream(FileName);
File outputsheetfile1 = new File(FileName);
if(outputsheetfile1.exists())
{
System.out.println("File existed");
try
{
XSSFWorkbook ObjWorkBook = new XSSFWorkbook(fileInputStream3);
XSSFSheet DriverTableSheet = ObjWorkBook.getSheetAt(0);
for(int i=1;i<3;i++)
{
XSSFRow row1 = DriverTableSheet.getRow(i);
XSSFCell Cell1 = row1.getCell(0);
System.out.println("Cell1"+ Cell1);
//System.out.println("Cell2"+ Cell2);
String str = "Abc";
Cell1.setCellValue(str);
FileOutputStream out1 = new FileOutputStream (FileName,false);
ObjWorkBook.write(out1);
fileInputStream3.close();
}
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Error I am getting is:
ObjWorkBook.write(out1);
`"poi-bin-3.9-20121203\poi-3.9\poi-ooxml-3.9-20121203.jar has no source attachment"`

HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Course Pack Resolution Details");
outputFileName = outPut.getAbsolutePath();
int rownum = 0;`enter code here`
for (int i = 0; i < dataList.size(); i++) {
Object[] objArr = dataList.get(i);
HSSFRow row = sheet.createRow(rownum++);
int cellnum = 0;
for (Object obj : objArr) {
Cell cell = row.createCell(cellnum++);
sheet.autoSizeColumn((short) cellnum);
if (obj instanceof Date) {
cell.setCellValue((Date) obj);
} else if (obj instanceof Boolean) {
cell.setCellValue((Boolean) obj);
} else if (obj instanceof String) {
cell.setCellValue((String) obj);
} else if (obj instanceof Double) {
cell.setCellValue((Double) obj);
}
}
}
if (outPut.exists()) {
outPut.delete();
}
FileOutputStream out =
new FileOutputStream(outPut);
workbook.write(out);
DataList is ArrayList of Array Object so you can enter as much data as you want init.
Example of DataList:
dataList.add(new Object[]{"Sr No.", "Cols1", "cols2", "cols3"......."colsn"});
respective data you can insert in list. this example is for .xls format if you want .xlsx then use xssfworkbook.
May be help you.

The error you mentioned:
ObjWorkBook.write(out1); Here it is showing Error as "poi-bin-3.9-20121203\poi-3.9\poi-ooxml-3.9-20121203.jar has no source attachment"
Does not seem to be anyways related to the problem you mentioned about writing data in multiple cells to excel.
You may want to look at this:
How can I link source to a jar package in eclipse?

=======write data in excel-file in play framework===============
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Sample sheet");
Map<String, Object[]> data = new HashMap<String, Object[]>();
data.put("1", new Object[] {"empNo.", "name", "salary"});
data.put("2", new Object[] {1, "John", 1500000d});
data.put("3", new Object[] {2, "Sam", 800000d});
data.put("4", new Object[] {3, "Dean", 700000d});
Set<String> keyset = data.keySet();
int rownum = 0;
for (String key : keyset) {
Row row = sheet.createRow(rownum++);
Object [] objArr = data.get(key);
int cellnum = 0;
for (Object obj : objArr) {
Cell cell = row.createCell(cellnum++);
if(obj instanceof Integer)
cell.setCellValue((Integer)obj);
else if(obj instanceof String)
cell.setCellValue((String)obj);
else if(obj instanceof Double)
cell.setCellValue((Double)obj);
}
}
try {
//new excel file created by fileoutput stream object
FileOutputStream out =
new FileOutputStream(new File("/home/jagasan/workspace-playexcelApp/public/ExcelFile3.xlsx"));
workbook.write(out);
out.close();
System.out.println("Excel written successfully..");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return ok("file reading is completed");
=======read data from excel and store in database in playframework=======
public class Application extends Controller {
/*
* public Result index() { return
* ok(index.render("Your new application is ready.")); }
*/
public Result readExcel() throws FileNotFoundException {
try{
InputStream ExcelFileToRead = new FileInputStream("/home/jagasan/workspace-play/excelApp/public/ExcelFile3.xlsx");
HSSFWorkbook wb = new HSSFWorkbook(ExcelFileToRead);
HSSFSheet sheet=wb.getSheetAt(0);
HSSFRow row;
HSSFCell cell;
Iterator rows = sheet.rowIterator();
boolean flag=false;
while (rows.hasNext())
{
row=(HSSFRow) rows.next();
if(flag==false)
{
flag=true;
continue;
}
Iterator cells = row.cellIterator();
ExcelFile excelfile=new ExcelFile();
int i=0;
while (cells.hasNext())
{
cell=(HSSFCell) cells.next();
if(i==0)
excelfile.setEmpNo((int)cell.getNumericCellValue());
if(i==1)
excelfile.setName(cell.getStringCellValue());
if(i==2)
excelfile.setSalary(cell.getNumericCellValue());
i++;
}
excelfile.save();
}
}
catch(Exception e)
{
e.printStackTrace();
System.out.println("error");
}
return ok("successful");
}
======in build.sbt=======
use the dependency jar file means apache API
libraryDependencies ++= Seq(
javaJdbc,
cache,
javaWs,
"org.apache.poi" % "poi" % "3.8", "org.apache.poi" % "poi-ooxml" % "3.9"
)

Related

Unable to write to Excel using Selenium webdriver

I have created a test where I am reading from excel and iterating through a worksheet to process an application in a web portal. This is working as expected.
However I am now trying to write results from the web page into another sheet on the same excel. The test case I am running passes in Eclipse but no data is written to the specified sheet. (I'm also looking to iterate on the results sheet to capture multiple application records, haven't got to that part yet).
Please see below my test script and the methods I have created in an ExcelConfig util sheet. Hoping someone can advise where I'm going wrong, thanks in advance.
Steve
Test Case
package com.htb.puma.uatTests;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import com.htb.puma.pages.SMcaseHeader;
import com.htb.puma.pages.SMhome;
import com.htb.puma.pages.SMloanDetails;
import com.htb.puma.pages.SMlogin;
import com.htb.puma.pages.SetUpConfig;
import com.htb.puma.util.ExcelConfig;
import org.openqa.selenium.Keys;
import org.openqa.selenium.NoAlertPresentException;
import java.io.File;
import java.io.IOException;
public class THAM_WRITE_Test {
WebDriver driver;
#Test
public void specMortHome() throws NoAlertPresentException, InterruptedException, IOException {
// calling drivers from the SetUpConfig page
driver = SetUpConfig.getChromeDriver();
// driver = SetUpConfig.getFirefoxDriver();
// driver = SetUpConfig.getIEDriver();
String path = new File("src/test/resources/TestData.xlsx").getAbsolutePath();
ExcelConfig excel = new ExcelConfig(path);
int row = 1;
while (excel.getData("PDFRollUp", row, 0) != "") {
String loanAmReq = excel.getNumericData("PDFRollUp", row, 6);
// LOGIN
SMlogin specMortLogin = new SMlogin(driver);
specMortLogin.openSMlogin();
specMortLogin.maximiseWindow();
specMortLogin.enterUsername("OpsAdminAuto");
specMortLogin.enterPassword("AutoOps123!");
specMortLogin.clickSignInBtn();
Thread.sleep(2000);
SMhome specMortHome = new SMhome(driver);
specMortHome.clickTopMC();
Thread.sleep(2000);
SMcaseHeader specMortCaseHeader = new SMcaseHeader(driver);
specMortCaseHeader.clickLoanDetailsTab();
SMloanDetails specMortLoanDetails = new SMloanDetails(driver);
Thread.sleep(2000);
specMortLoanDetails.enterLoanAmReq(Keys.CONTROL + "a"); // PDF
specMortLoanDetails.enterLoanAmReq(loanAmReq); // PDF
String erc = specMortLoanDetails.getERC();
String ltv = specMortLoanDetails.getLTV();
excel.createFile("src/test/resources/TestData.xlsx");
excel.writeStringData("Results", 1, 1, erc);
excel.writeStringData("Results", 1, 2, ltv);
specMortHome.clickUserActionsHomeLM();
specMortHome.clickLogoutHomeLM();
row++;
}
driver.quit();
}
}
Excel Config
package com.htb.puma.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Row;
public class ExcelConfig {
public XSSFWorkbook wb;
XSSFSheet sheet1;
public ExcelConfig(String Excelpath) {
File src = new File(Excelpath);
try {
FileInputStream fis = new FileInputStream(src);
wb = new XSSFWorkbook(fis);
} catch (Exception e) {
System.out.println("Excel file not loaded");
}
}
// reads the string in the excel file
public String getData(String sheetName, int row, int column) {
sheet1 = wb.getSheet(sheetName);
String data = "";
try {
data = sheet1.getRow(row).getCell(column).getStringCellValue();
} catch (NullPointerException e) {
data = "";
}
return data;
}
// reads the number in the excel file
public String getNumericData(String sheetName, int row, int column) {
sheet1 = wb.getSheet(sheetName);
String data = "";
try {
// data = sheet.getRow(row).getCell(column).getRawValue();
DataFormatter dataFormatter = new DataFormatter();
Cell cell = sheet1.getRow(row).getCell(column);
data = dataFormatter.formatCellValue(cell);
} catch (NullPointerException e) {
data = "";
}
return data;
}
//write string data into excel
public void writeStringData(String sheetName, int row, int column, String data) {
sheet1 = wb.getSheet(sheetName);
Row valueRow = sheet1.getRow(row);
Cell valueCell = valueRow.createCell(column);
if (data.equals("FAILED")) {
CellStyle style = wb.createCellStyle();
Font font = wb.createFont();
//font.setColor(HSSFColor.RED.index);
style.setFont(font);
valueCell.setCellValue(data);
valueCell.setCellStyle(style);
}
valueCell.setCellValue(data);
}
//creates an excel file
public void createFile(String path) {
File src = new File(path);
try {
FileOutputStream outputStream = new FileOutputStream(src);
try {
wb.write(outputStream);
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
write(java.io.OutputStream stream) is used to write data to the excel file
public void writeStringData(String sheetName, int row, int column, String data) {
try {
sheet1 = wb.getSheet(sheetName);
Row valueRow = sheet1.getRow(row);
Cell valueCell = valueRow.createCell(column);
if (data.equals("FAILED")) {
CellStyle style = wb.createCellStyle();
Font font = wb.createFont();
//font.setColor(HSSFColor.RED.index);
style.setFont(font);
valueCell.setCellValue(data);
valueCell.setCellStyle(style);
}
valueCell.setCellValue(data);
FileOutputStream fout;
fout = new FileOutputStream(new File("<path>"));
//fout = new FileOutputStream("src/test/resources/TestData.xlsx" );
wb.write(fout);
// fout.flush();
wb.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (EncryptedDocumentException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

Error in opening an mail attached excel file created using Apache POI

I am creating an excel sheet using Apache POI and then sending the same file using Java GWT.The file created is all right.Now in the mail there are two options- Save or open.When I save the file in machine it is working fine but when I try to open ,it opens in notepad.In the suggestion too it is not showing excel. Here is my code to create the excel sheet:
package com.ericsson.egi.sxs.utils;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import com.ericsson.egi.sxs.persistence.entity.AssetOrder;
public class CreateExcelFile {
int rownum = 0;
HSSFSheet firstSheet;
Collection<File> files;
HSSFWorkbook workbook;
CreateExcelFile() {
}
public File createWeeklyReport(List<AssetOrder> tempOrderList) throws Exception {
workbook = new HSSFWorkbook();
firstSheet = workbook.createSheet("FIRST SHEET");
List<String> headerRow = new ArrayList<String>();
headerRow.add("Name of Supplier/Vendor");
headerRow.add("Description of Contract");
headerRow.add("Initiator");
headerRow.add("Type Of Contract");
headerRow.add("Template Source");
headerRow.add("Savings");
headerRow.add("Payment Term");
headerRow.add("Code of Conduct Signed by Supplier");
headerRow.add("RoHS clause Included");
headerRow.add("Agreement No");
headerRow.add("Agreement Validity From ");
headerRow.add("Agreement Validity To");
headerRow.add("Sanctioned Parties List Screening");
headerRow.add("Sanctioned Parties List Screening Reasons in case no answer NO");
headerRow.add("Registered in CLM");
headerRow.add("Registered in CLM reasons if answer NO");
headerRow.add("Current State");
headerRow.add("Next State");
headerRow.add("TAT for L1");
headerRow.add("TAT for L2");
headerRow.add("TAT for L3");
headerRow.add("TAT for L4");
headerRow.add("Current State Comments");
List<List> recordToAdd = new ArrayList<List>();
recordToAdd.add(headerRow);
for (AssetOrder order : tempOrderList ) {
List<String> row = new ArrayList<String>();
row.add(order.getSourcingDetails().getVendorName());
row.add(order.getSourcingDetails().getContractDescription());
row.add(order.getSourcingDetails().getInitiatorName());
row.add(order.getSourcingDetails().getContractType());
row.add(order.getSourcingDetails().getTemplateSource());
row.add(order.getSourcingDetails().getSavings());
row.add(order.getSourcingDetails().getPaymentTerm());
if (order.getSourcingDetails().getIsCOCSigned()) {
row.add("YES");
} else {
row.add("NO");
}
if (order.getSourcingDetails().getIsROHSIncluded()) {
row.add("YES");
} else {
row.add("NO");
}
row.add(order.getSourcingDetails().getAgreementNo());
row.add(order.getSourcingDetails().getValidityFrom().toString());
row.add(order.getSourcingDetails().getValidityTo().toString());
if (order.getSourcingDetails().getIsSPLScreening()) {
row.add("YES");
} else {
row.add("NO");
}
row.add(order.getSourcingDetails().getReasonsForSPL());
if (order.getSourcingDetails().getIsRegisteredInCLM()) {
row.add("YES");
} else {
row.add("NO");
}
row.add(order.getSourcingDetails().getReasonsForCLM());
row.add(order.getStatusMaster().getStatusName());
row.add(null);
row.add(null);
row.add(null);
row.add(null);
row.add(null);
row.add(order.getComments());
recordToAdd.add(row);
}
CreateExcelFile cls = new CreateExcelFile(recordToAdd);
File file = cls.createExcelFile(tempOrderList.get(0).getOrderRequesterSignum());
return file;
}
File createExcelFile(String requesterSignum) {
FileOutputStream fos = null;
File file = new File("/tmp/" + requesterSignum + "_StatusReport.xls");
try {
fos=new FileOutputStream(file);
HSSFCellStyle hsfstyle=workbook.createCellStyle();
hsfstyle.setBorderBottom((short) 1);
hsfstyle.setFillBackgroundColor((short)245);
workbook.write(fos);
} catch (Exception e) {
e.printStackTrace();
}
return file;
}
CreateExcelFile(List<List> l1) throws Exception {
try {
workbook = new HSSFWorkbook();
firstSheet = workbook.createSheet("FIRST SHEET");
for (int j = 0; j < l1.size(); j++) {
Row row = firstSheet.createRow(rownum);
List<String> l2= l1.get(j);
for(int k=0; k<l2.size(); k++)
{
Cell cell = row.createCell(k);
cell.setCellValue(l2.get(k));
}
rownum++;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
}
}
}
Try with other Excel Extension as per your Excel version installed on your machine.
--EDIT--
May be the issue is related to Content Type. Please confirm what are you using for this?
response.setContentType("APPLICATION/OCTET-STREAM");
// try this one if above doesn't work
//response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-disposition", "attachment;filename=myExcel.xls");

Reading Excel Rows and Columns

The code below is to read a large excel file. I got an "Cannot get a text value from a numeric cell at org.apache.poi.hssf.usermodel.HSSFCell.typeMismatch" error. How do I fix this. Column 1 is Numerical Value, Column 2 is String Value.
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFCell;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.Vector;
public class ReadExcel {
public static void main(String[] args) throws Exception {
String filename = "C:/Documents and Settings/oemiola/My Documents/Defects_Input.xls";
FileInputStream fis = null;
try {
fis = new FileInputStream(filename);
HSSFWorkbook workbook = new HSSFWorkbook(fis);
HSSFSheet sheet = workbook.getSheetAt(0);
Iterator rowIter = sheet.rowIterator();
while(rowIter.hasNext()){
HSSFRow myRow = (HSSFRow) rowIter.next();
Iterator cellIter = myRow.cellIterator();
Vector<String> cellStoreVector=new Vector<String>();
while(cellIter.hasNext()){
HSSFCell myCell = (HSSFCell) cellIter.next();
String cellvalue = myCell.getStringCellValue();
cellStoreVector.addElement(cellvalue);
}
String firstcolumnValue = null;
String secondcolumnValue = null;
int i = 0;
firstcolumnValue = cellStoreVector.get(i).toString();
secondcolumnValue = cellStoreVector.get(i+1).toString();
insertQuery(firstcolumnValue,secondcolumnValue);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null) {
fis.close();
}
}
}
private static void insertQuery(String firstcolumnvalue,String secondcolumnvalue) {
System.out.println(firstcolumnvalue + " " +secondcolumnvalue);
}
}
Use Cell#getCellType to determine whether there is a number or a string in the cell. If it's numeric, then use getNumericCellValue instead of getStringCellValue.

How to dynamically generate multiple worksheets in apache poi

I would like to dynamically generate multiple worksheets for a workbook/excel in Apache poi. I want to know how can I do it an efficient and thread safe/concurrent way.
So multiple worksheet dynamically with the option to name them.
Each worksheet will have their own set of columns etc ( or style).
Write return those back in a servlet etc.
Please help.
Thank you.
like this?
public static void createExcel(String excelFilePath, String sheetName)
throws IOException {
FileOutputStream fos = null;
try {
HSSFWorkbook workbook = null;
if (new File(excelFilePath).createNewFile()) {
workbook = new HSSFWorkbook();
} else {
POIFSFileSystem pfs = new POIFSFileSystem(new FileInputStream(
new File(excelFilePath)));
workbook = new HSSFWorkbook(pfs);
}
if (workbook.getSheet(sheetName) == null) {
fos = new FileOutputStream(excelFilePath);
workbook.createSheet(sheetName);
workbook.write(fos);
}
} catch (IOException e) {
throw e;
} finally {
if (fos != null) {
fos.close();
}
}
}
Please find the sample code.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
public class ExcelUtility {
public static boolean writeDataSheetWise(final String excelFileName, final List<String> headers,
Map<String, List<Object[]>> sheetRowDataList) throws IOException, InvalidFormatException {
boolean isWritten = false;
HSSFWorkbook workbook = new HSSFWorkbook();
for(String sheetName: sheetRowDataList.keySet()) {
createSheet(workbook, sheetName, headers, sheetRowDataList.get(sheetName));
}
try {
System.out.println("\nWritting data to excel file <" + excelFileName + ">");
FileOutputStream outputStream = new FileOutputStream(new File(excelFileName));
workbook.write(outputStream);
outputStream.flush();
outputStream.close();
isWritten = true;
System.out.println("\nData is successfully written to excel file <"+excelFileName+">.");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return isWritten;
}
public static boolean writeData(final String excelFileName, final String sheetName, final List<String> headers,
List<Object[]> rowDataList) throws IOException, InvalidFormatException {
boolean isWritten = false;
HSSFWorkbook workbook = new HSSFWorkbook();
createSheet(workbook, sheetName, headers, rowDataList);
try {
System.out.println("\nWritting data to excel file <" + excelFileName + ">");
FileOutputStream outputStream = new FileOutputStream(new File(excelFileName));
workbook.write(outputStream);
outputStream.flush();
outputStream.close();
isWritten = true;
System.out.println("\nData is successfully written to excel file <"+excelFileName+">.");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return isWritten;
}
#SuppressWarnings("deprecation")
private static void createSheet(final HSSFWorkbook workbook, final String sheetName, final List<String> headers,
final List<Object[]> rowDataList) {
HSSFSheet sheet = workbook.createSheet(sheetName);
int rowCount = 0;
HSSFCellStyle style = workbook.createCellStyle();
HSSFFont headersFont = workbook.createFont();
headersFont.setFontName(HSSFFont.FONT_ARIAL);
headersFont.setFontHeightInPoints((short) 16);
headersFont.setColor(HSSFColor.GREEN.index);
headersFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
style.setFont(headersFont);
// Creating header row
Row headerRow = sheet.createRow(rowCount++);
for (int i = 0; i < headers.size(); i++) {
Cell cell = headerRow.createCell(i);
cell.setCellStyle(style);
cell.setCellValue(headers.get(i));
sheet.autoSizeColumn(i);
}
for (Object rowDataObject[] : rowDataList) {
Row row = sheet.createRow(rowCount++);
int cellnum = 0;
for (Object rowData : rowDataObject) {
Cell cell = row.createCell(cellnum++);
if (rowData instanceof Date)
cell.setCellValue((Date) rowData);
else if (rowData instanceof Boolean)
cell.setCellValue((Boolean) rowData);
else if (rowData instanceof String)
cell.setCellValue((String) rowData);
else if (rowData instanceof Integer)
cell.setCellValue((Integer) rowData);
else if (rowData instanceof Long)
cell.setCellValue((Long) rowData);
else if (rowData instanceof Double)
cell.setCellValue((Double) rowData);
}
}
}
}

Writing to a existing xls file using POI

The scenario is roughly this:
I have a java program with several methods getting called randomly.
The first method will create an xls file using apache POI and will put the headers for the columns.
All the other methods has to write a record into this file.
The final method will first mail the created xls and then delete the xls.
For above scenario is the below approach correct:
1) Create the file and put the header names in the first method:
Workbook wb = new HSSFWorkbook();
CreationHelper createHelper = wb.getCreationHelper();
Sheet sheet = wb.createSheet("First Sheet");
Row row = sheet.createRow((short)0);
row.createCell(1).setCellValue(createHelper.createRichTextString("First Column"));
row.createCell(2).setCellValue(createHelper.createRichTextString("Second Column"));
row.createCell(3).setCellValue(createHelper.createRichTextString("Third Column"));
// Write the output to a file
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();
2) In the remaining methods put the records:
I am not sure of the code here. I know that I can reach the end of the sheet using getRowCount method and then add the new row. But I could not find any example code.
Also, how to access the existing xls file ?
3) In the last method, the file will be mailed and then deleted.
Do I need to perform any other steps before deleting the file ?
This was what I was looking for:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.Font;
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;
public class PoiWriteExcelFile {
public void methodOne() {
System.out.println("Into method one!");
Workbook wb = new HSSFWorkbook();
Font f = wb.createFont();
f.setBoldweight(Font.BOLDWEIGHT_BOLD);
CellStyle cs = wb.createCellStyle();
cs.setFont(f);
CreationHelper createHelper = wb.getCreationHelper();
Sheet sheet = wb.createSheet("First Sheet");
Row row = sheet.createRow((short) 0);
Cell c = null;
c = row.createCell(0);
c.setCellStyle(cs);
c.setCellValue(createHelper.createRichTextString("First Column"));
c = row.createCell(1);
c.setCellStyle(cs);
c.setCellValue(createHelper.createRichTextString("Second Column"));
c = row.createCell(2);
c.setCellStyle(cs);
c.setCellValue(createHelper.createRichTextString("Third Column"));
// Write the output to a file
FileOutputStream fileOut;
try {
fileOut = new FileOutputStream("C:\\TestData\\POI\\poi-test.xls");
wb.write(fileOut);
fileOut.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Out of method one!");
}
public void methodTwo() {
System.out.println("Into method two!");
InputStream inp;
try {
inp = new FileInputStream("C:\\TestData\\POI\\poi-test.xls");
Workbook wb = WorkbookFactory.create(inp);
Sheet sheet = wb.getSheetAt(0);
Row row = sheet.createRow((short) (sheet.getLastRowNum() + 1));
Cell c = null;
CreationHelper createHelper = wb.getCreationHelper();
c = row.createCell(0);
c.setCellValue(createHelper.createRichTextString("First Row First value"));
c = row.createCell(1);
c.setCellValue(createHelper.createRichTextString("First Row Second value"));
c = row.createCell(2);
c.setCellValue(createHelper.createRichTextString("First Row Third value"));
FileOutputStream fileOut = new FileOutputStream("C:\\TestData\\POI\\poi-test.xls");
wb.write(fileOut);
fileOut.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (InvalidFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Out of method two!");
}
public void methodThree() {
System.out.println("Into method three!");
InputStream inp;
try {
inp = new FileInputStream("C:\\TestData\\POI\\poi-test.xls");
Workbook wb = WorkbookFactory.create(inp);
Sheet sheet = wb.getSheetAt(0);
Row row = sheet.createRow((short) (sheet.getLastRowNum() + 1));
Cell c = null;
CreationHelper createHelper = wb.getCreationHelper();
c = row.createCell(0);
c.setCellValue(createHelper.createRichTextString("Second Row First value"));
c = row.createCell(1);
c.setCellValue(createHelper.createRichTextString("Second Row Second value"));
c = row.createCell(2);
c.setCellValue(createHelper.createRichTextString("Second Row Third value"));
FileOutputStream fileOut = new FileOutputStream("C:\\TestData\\POI\\poi-test.xls");
wb.write(fileOut);
fileOut.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (InvalidFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Out of method three!");
}
public void methodFour() {
System.out.println("Into method four!");
File file = new File("C:\\TestData\\POI\\poi-test.xls");
// file.deleteOnExit();
System.out.println("Out of method four!");
}
public static void main(final String[] args) {
PoiWriteExcelFile myObj = new PoiWriteExcelFile();
myObj.methodOne();
myObj.methodTwo();
myObj.methodThree();
myObj.methodFour();
}
}

Categories

Resources