Here is my excel utils class:
package utility;
import java.io.FileInputStream;
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;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.CellType;
public class ExcelUtils {
private static XSSFSheet ExcelWSheet;
private static XSSFWorkbook ExcelWBook;
private static XSSFCell cell;
private static XSSFRow row;
//This method is to set the File path and to open the Excel
file, Pass Excel Path and Sheetname as Arguments to this method
public static void setExcelFile(String Path, String SheetName) throws Exception {
try {
// Open the Excel file
FileInputStream ExcelFile = new FileInputStream(Path);
// Access the required test data sheet
ExcelWBook = new XSSFWorkbook(ExcelFile);
ExcelWSheet = ExcelWBook.getSheet(SheetName);
} catch (Exception e) {
throw (e);
}
}
//This method is to read the test data from the Excel cell, in this we are passing parameters as Row num and Col num
public static String getCellData(int RowNum, int ColNum) throws Exception {
try {
String cellData = "";
cell = ExcelWSheet.getRow(RowNum).getCell(ColNum);
cell.setCellType(CellType.STRING);
cellData = cell.getStringCellValue();
return cellData;
} catch (Exception e) {
return "undefined";
}
}
//This method is to write in the Excel cell, Row num and Col num are the parameters
public static void setCellData(String Result, int RowNum, int ColNum) throws Exception {
try {
row = ExcelWSheet.getRow(RowNum);
cell = row.getCell(ColNum, Row.MissingCellPolicy.RETURN_BLANK_AS_NULL);
if (cell == null) {
cell = row.createCell(ColNum);
cell.setCellValue(Result);
} else {
cell.setCellValue(Result);
}
// Constant variables Test Data path and Test Data file name
FileOutputStream fileOut = new FileOutputStream(Constants.Path_TestData + Constants.File_TestData);
ExcelWBook.write(fileOut);
fileOut.flush();
fileOut.close();
} catch (Exception e) {
throw (e);
}
}
}
Here is the script where I'm calling the getCellData to get the values from Excel:
String cellData = ExcelUtils.getCellData(1, 1);
System.out.println("CellData :" + cellData);
Here is the excel file format:
TestCaseName | Username | Password
TC_01 | TestData |
Output:
Exception in thread "main" java.lang.NullPointerException
at utility.ExcelUtils.getCellData(ExcelUtils.java:63)
at testScripts.Category_creation.main(Category_creation.java:47)
Here is the excel I'am using. Not able to fetch data from excel file. I'm using Page object framework, hence the excel utils file contains only the code and in fetching the data in testScript by passing row and column number.
POI 3.9
please add cell.setCellType(Cell.CELL_TYPE_STRING); after cell = ExcelWSheet.getRow(RowNum).getCell(ColNum);
i.e.
import org.apache.poi.ss.usermodel.Cell;
...
try{
cell = ExcelWSheet.getRow(RowNum).getCell(ColNum);
cell.setCellType(Cell.CELL_TYPE_STRING);
String CellData = cell.getStringCellValue();
return CellData;
}catch (Exception e){
return"";
}
or you can use this construct
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getStringCellValue() + "\t");
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.print(cell.getNumericCellValue() + "\t");
break;
case Cell.CELL_TYPE_BOOLEAN:
System.out.print(cell.getBooleanCellValue() + "\t");
break;
default:
source http://www.java67.com/2014/09/how-to-read-write-xlsx-file-in-java-apache-poi-example.html
and please rename the variable private static XSSFCell Cell; to cell. (Variable naming conventions in Java?)
UPDATE 1
POI 3.17 you could also uncomment switch-case block, it works for POI 3.17
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.io.IOUtils;
import org.apache.poi.ss.usermodel.CellType;
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 Excel {
private static XSSFSheet ExcelWSheet;
private static XSSFWorkbook ExcelWBook;
private static XSSFCell xCell;
private static XSSFRow xRow;
public static void main(String... args) {
try {
InputStream is = readInputStreamFromFile();
XSSFWorkbook myWorkBook = new XSSFWorkbook(is);
XSSFSheet mySheet = myWorkBook.getSheetAt(0);
ExcelWSheet = mySheet;
System.out.println(getCellData(1, 0));
System.out.println(getCellData(1, 1));
is.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static String getCellData(int RowNum, int ColNum) throws Exception{
try {
String cellData = "";
xCell = ExcelWSheet.getRow(RowNum).getCell(ColNum);
xCell.setCellType(CellType.STRING);
cellData = xCell.getStringCellValue();
// switch (xCell.getCellTypeEnum()) {
// case STRING:
// //System.out.print(xCell.getStringCellValue() + "\t");
// cellData = xCell.getStringCellValue();
// break;
// case NUMERIC:
// cellData = String.valueOf(xCell.getNumericCellValue());
// //System.out.print(xCell.getNumericCellValue() + "\t");
// break;
// case BOOLEAN:
// cellData = String.valueOf(xCell.getBooleanCellValue());
// //System.out.print(xCell.getBooleanCellValue() + "\t");
// break;
//
// default:
// cellData = "undefined";
// }
return cellData;
} catch (Exception e){
return "undefined";
}
}
private static InputStream readInputStreamFromFile() throws Exception {
try {
File f = new File("C:\\path to your file\\TestData.xlsx");
InputStream is = new FileInputStream(f);
try {
return new ByteArrayInputStream(IOUtils.toByteArray(is));
} finally {
is.close();
}
} catch (IOException e) {
throw new Exception(e);
}
}
}
Related
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();
}
}
Earlier I was using SAX parser for export to excel. Now I am not able to get data using Apache POI, Any suggestion???
This String in XML contains all the data which I retrieved through farpoint grid tech and set in the form in action class.
private void parseXML(String inXML) {
/* // get a factory
SAXParserFactory spf = SAXParserFactory.newInstance();
try {
// get a new instance of parser
SAXParser sp = spf.newSAXParser();
// parse the file
sp.parse(new InputSource(new StringReader(inXML)), this);
} catch (IOException ie) {
}*/
Now I am using this.
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Sample sheet");
short rowNum = 0;
short colNum = 0;
Row row = sheet.createRow(rowNum++);
Cell cell = row.createCell(colNum);
cell.setCellValue(inXML);
**/* Iterator<Row> rowIterator = sheet.iterator();
while(rowIterator.hasNext()) {
Row row = rowIterator.next();
//For each row, iterate through each columns
Iterator<Cell> cellIterator = row.cellIterator();
while(cellIterator.hasNext()) {
Cell cell = cellIterator.next();
cell.setCellValue(inXML);
switch(cell.getCellType()) {
case Cell.CELL_TYPE_BOOLEAN:
System.out.print(cell.getBooleanCellValue() + "\t\t");
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.print(cell.getNumericCellValue() + "\t\t");
break;
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getStringCellValue() + "\t\t");
break;
}
}*/**
try {
FileOutputStream out = new FileOutputStream(new File("C:\\Excel.xls"));
workbook.write(out);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
This program (which is what you posted with added imports, without the comment block, with a literal string instead of the variable inXML and with the path removed from the output file):
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
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.ss.usermodel.Cell;
public class Main {
public Main() {
// TODO Auto-generated constructor stub
}
public static void main(String[] args) {
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Sample sheet");
short rowNum = 0;
short colNum = 0;
HSSFRow row = sheet.createRow(rowNum++);
Cell cell = row.createCell(colNum);
cell.setCellValue("<data>test data</data>");
try {
FileOutputStream out = new FileOutputStream(new File("Excel.xls"));
workbook.write(out);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Produced exactly what you would expect: A spreadsheet with <data>test data</data> in cell A1.
Perhaps cell A1 in your spreadsheet is blank because inXML really is blank.
I am trying to use XLS2CSV to convert an Excel file to a csv text file. I modified the existing class slightly to change PrintStream to Writer so I could write to a file using FileWriter.
Anyway, it writes to the System.out.PrintStream fine, everything shows up. But when I open the file the last few lines are missing. My first assumption was that the application was closing the connection before it could complete the writes but I used an infinite loop to try and test that but even leaving the application open it does the same thing.
Does anyone have any ideas why this will print to PrintStream fine but not write to a file? I changed the FileWriter to CSVWriter and it seemed to write less data so I'm thinking it does have something to do with the connection getting closed but I'm fairly new to input and output so any help would be appreciated.
Here is a functional example (you'll need to modify the file name for the input and output)
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.Writer;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator;
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.CellValue;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.ss.usermodel.Row;
public class XLS2CSV {
private InputStream in;
private Writer out;
private DateFormat dateFormat = new SimpleDateFormat("dd/MM/yy");
public XLS2CSV(InputStream in, Writer out) {
if (null == in) {
throw new IllegalArgumentException("in cannot be null.");
}
if (null == out) {
throw new IllegalArgumentException("out cannot be null.");
}
this.in = in;
this.out = out;
}
public void process() throws IOException {
process(in);
}
private void process(InputStream in) throws IOException {
HSSFWorkbook w = new HSSFWorkbook(in);
int numSheets = w.getNumberOfSheets();
for (int i = 0; i < numSheets; i++) {
HSSFSheet sheet = w.getSheetAt(i);
int lastRow = 0;
for (Iterator rows = sheet.rowIterator(); rows.hasNext();) {
Row row = (Row) rows.next();
int lastCol = 0;
for (Iterator cells = row.cellIterator(); cells.hasNext();) {
Cell cell = (Cell) cells.next();
String cellValue = "";
switch (cell.getCellType()) {
case Cell.CELL_TYPE_FORMULA:
FormulaEvaluator fe = new HSSFFormulaEvaluator(w);
CellValue v = fe.evaluate(cell);
switch (v.getCellType()) {
case Cell.CELL_TYPE_BOOLEAN:
cellValue = String.valueOf(v.getBooleanValue());
break;
case Cell.CELL_TYPE_NUMERIC:
cellValue = String.valueOf(v.getNumberValue());
break;
case Cell.CELL_TYPE_STRING:
cellValue = String.valueOf(v.getStringValue());
break;
case Cell.CELL_TYPE_BLANK:
break;
case Cell.CELL_TYPE_ERROR:
break;
// CELL_TYPE_FORMULA will never happen
case Cell.CELL_TYPE_FORMULA:
break;
}
break;
case Cell.CELL_TYPE_NUMERIC:
if (HSSFDateUtil.isCellDateFormatted(cell)) {
Date date = cell.getDateCellValue();
cellValue = dateFormat.format(date);
} else {
cellValue = String.valueOf(cell);
}
break;
default:
cellValue = String.valueOf(cell);
}
int cellIndex = cell.getColumnIndex();
while (lastCol < cellIndex) {
System.out.print(",");
out.append(",");
lastCol++;
}
System.out.print(cellValue);
out.append(cellValue);
}
while (lastRow <= row.getRowNum()) {
System.out.println();
out.append('\n');
lastRow++;
}
}
}
}
public void setDateFormat(DateFormat dateFormat) {
if (null == dateFormat) {
throw new IllegalArgumentException("dateFormat cannot be null.");
}
this.dateFormat = dateFormat;
}
public DateFormat getDateFormat() {
return dateFormat;
}
public static void process(File file, Writer out) throws IOException {
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
new XLS2CSV(new BufferedInputStream(fis), out).process();
} finally {
if (null != fis) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
File xlsFile = new File("C:/Documents and Settings/berlgeof/Desktop/Commit Dates 12-10-2013.xls");
if (!xlsFile.exists()) {
System.err.println("Not found or not a file: " + xlsFile.getPath());
return;
}
Writer writer = null;
try {
writer = new FileWriter("lib/files/converted/Temp Commit Data.csv");
} catch (IOException e) {
e.printStackTrace();
}
XLS2CSV xls2csv = null;
try {
xls2csv = new XLS2CSV(new FileInputStream(xlsFile), writer);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
xls2csv.process();
} catch (IOException e) {
e.printStackTrace();
}
// while(true) {} // Let me close the application
}
You're not closing the writer, which means there's data still in the buffer. You should close it (and all the other streams etc) in finally blocks, or use a try-with-resources statement if you're using Java 7.
Also note that the way you're currently "handling" exceptions is to pretty much ignore them and proceed - which means that after one thing's failed, you'll almost certainly get another failure. Rip out those try/catch blocks, and just let the exception propagate up. (Declare that your main method can throw IOException.)
I have some Java code which reads the Excel data. On running the Java code, it's showing the following error. Help me resolve the same. Also, I need to know other method of reading .xlsx file.
(A small edit) how I can print rows with their respective columns. For example:
Age
19
20
21
Salary
35k
20k
40k
.
.
.
Exception in thread "main"
org.apache.poi.poifs.filesystem.OfficeXmlFileException: The supplied
data appears to be in the Office 2007+ XML. You are calling the part
of POI that deals with OLE2 Office Documents. You need to call a
different part of POI to process this data (eg XSSF instead of HSSF)
at
org.apache.poi.poifs.storage.HeaderBlock.(HeaderBlock.java:131)
at
org.apache.poi.poifs.storage.HeaderBlock.(HeaderBlock.java:104)
at
org.apache.poi.poifs.filesystem.POIFSFileSystem.(POIFSFileSystem.java:138)
at
org.apache.poi.hssf.usermodel.HSSFWorkbook.(HSSFWorkbook.java:322)
at
org.apache.poi.hssf.usermodel.HSSFWorkbook.(HSSFWorkbook.java:303)
at ExcelRead.main(ExcelRead.java:18)
The Java code is as follows:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Iterator;
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;
public class ExcelRead {
public static void main(String[] args) {
try {
FileInputStream file = new FileInputStream(new File("C:/Users/vinayakp/Desktop/Book.xlsx"));
HSSFWorkbook workbook = new HSSFWorkbook(file);
HSSFSheet sheet = workbook.getSheetAt(0);
Iterator<Row> rowIterator = sheet.iterator();
while(rowIterator.hasNext()) {
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
while(cellIterator.hasNext()) {
Cell cell = cellIterator.next();
switch(cell.getCellType()) {
case Cell.CELL_TYPE_BOOLEAN:
System.out.print(cell.getBooleanCellValue() + "\t\t");
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.print(cell.getNumericCellValue() + "\t\t");
break;
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getStringCellValue() + "\t\t");
break;
}
}
System.out.println("");
}
file.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException ae) {
ae.printStackTrace();
}
}
}
If you want to read a .xls file you must use HSSF (it supports only .xls format) but for .xlsx files you must use XSSF or another higher version API.
After deleting previous imports class then try to add
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.ss.usermodel.WorkbookFactory;
private static void read(String path){
Workbook workbook = null;
FileInputStream fis = null;
try {
File source = new File(path);
if(source.exists()){
fis = new FileInputStream(source);
workbook = WorkbookFactory.create(source);
}else{
JOptionPane.showMessageDialog(null, "File path is not exist.", "Error", JOptionPane.ERROR_MESSAGE);
}
Sheet sheet = null;
int lastRowNum = 0;
int numSheets = workbook.getNumberOfSheets();
for(int i = 0; i < numSheets; i++) {
sheet = workbook.getSheetAt(i);
if(sheet.getPhysicalNumberOfRows() > 0) {
lastRowNum = sheet.getLastRowNum();
int lastCellNum = 0;
for(Row row : sheet) {
Employee emp = new Employee();
int numOfCell = row.getPhysicalNumberOfCells();
System.out.println("numOfCell:: "+numOfCell);
String stringValues [] = new String[numOfCell];
for(Cell cell : row) {
// cell = row.getCell(cellIndex);
int cellIndex = cell.getColumnIndex();
logger.info("cellIndex:: "+ cellIndex);
switch (cell.getCellType()) {
case Cell.CELL_TYPE_FORMULA:
// printValue = "FORMULA value=" + cell.getCellFormula();
stringValues[cellIndex] = cell.getCellFormula();
break;
case Cell.CELL_TYPE_NUMERIC:
//printValue = "NUMERIC value=" + cell.getNumericCellValue();
System.out.println("Value is numeric:: "+ cell.getNumericCellValue());
stringValues[cellIndex] = String.valueOf(cell.getNumericCellValue());
break;
case Cell.CELL_TYPE_STRING:
// printValue = "STRING value=" + cell.getStringCellValue();
stringValues[cellIndex] = cell.getStringCellValue();
break;
case Cell.CELL_TYPE_BLANK:
// printValue = "STRING value=" + cell.getStringCellValue();
stringValues[cellIndex] = cell.getStringCellValue();
break;
default:
}
}
}
}
}
}
} catch (InvalidFormatException e) {
logger.error(e.getMessage());
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
logger.error(e.getMessage());
} catch (IOException e) {
logger.error(e.getMessage());
e.printStackTrace();
}
catch (Exception e) {
logger.error(e.getMessage());
e.printStackTrace();
}
finally {
if (fis != null) {
try {
fis.close();
fis = null;
} catch (IOException ioEx) {
logger.error(ioEx.getMessage());
}
}
}
}
you are using the wrong class for reading the file HSSFWorkbook is for old excel format. use XSSFWorkbook instead
Edited:
copied from http://www.coderanch.com/t/463779/java/java/read-xlsx-sheet-Client-Side.
did u do the same thing?
try {
System.out.println("destDir==> "+destDir);
XSSFWorkbook workBook = new XSSFWorkbook(destDir);
XSSFSheet sheet = workBook.getSheetAt(0);
totalRows = sheet.getPhysicalNumberOfRows();
System.out.println("total no of rows >>>>"+totalRows);
} catch (IOException e) {
e.printStackTrace();
}
Edit 2:
Learn about apache POI from this link
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);
}
}
}
}