Poi Formula evaluation Error - java

I am using poi-3.8-20120326.jar and Excel 2007, trying to collect all the cell value in one list.
I am using formula for date increment operation. For example: =(i2+3) for k2 cell.
While evaluating this formula through my java code returns #VALUE! (i2 is a date cell.)

Without source it's hard to guess what's wrong, but I think that are two things that you may forget.
1) FormulaEvaluator
2) DataFormatter
Take a look at example.
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.FileNotFoundException;
public class CellReader {
private Workbook workbook;
private DataFormatter formatter;
private FormulaEvaluator evaluator;
private void openWorkbook(String file) throws FileNotFoundException,
IOException, InvalidFormatException {
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
workbook = WorkbookFactory.create(fis);
evaluator = workbook.getCreationHelper().createFormulaEvaluator();
formatter = new DataFormatter(true);
} finally {
if (fis != null) {
fis.close();
}
}
}
private void printXLSX() {
Sheet sheet = null;
Row row = null;
Cell cell = null;
int lastRowNum;
int lastCellNum;
sheet = workbook.getSheetAt(0);
lastRowNum = sheet.getLastRowNum();
for (int j = 0; j <= lastRowNum; j++) {
row = sheet.getRow(j);
if (row == null) {
continue;
}
lastCellNum = row.getLastCellNum();
for (int k = 0; k <= lastCellNum; k++) {
cell = row.getCell(k);
if (cell == null) {
continue;
}
if (cell.getCellType() != Cell.CELL_TYPE_FORMULA) {
System.out.println(formatter.formatCellValue(cell));
} else {
System.out.println(formatter.formatCellValue(cell,evaluator));
}
}
}
}
public static void main(String[] args) {
CellReader converter = null;
try {
converter = new CellReader();
converter.openWorkbook("a.xlsx");
converter.printXLSX();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}

Related

Incompatible operand types int and CellType

So I am trying to read an excel sheet using Java code. Below is the code:
package com.SfHawk.Utility;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
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;
import java.io.FileInputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class ExcelApiTest {
public FileInputStream fis = null;
public XSSFWorkbook workbook = null;
public XSSFSheet sheet = null;
public XSSFRow row = null;
public XSSFCell cell = null;
public ExcelApiTest(String xlFilePath) throws Exception
{
fis = new FileInputStream(xlFilePath);
workbook = new XSSFWorkbook(fis);
fis.close();
}
public String getCellData(String sheetName, String colName, int rowNum)
{
try
{
int col_Num = -1;
sheet = workbook.getSheet(sheetName);
row = sheet.getRow(0);
for(int i = 0; i < row.getLastCellNum(); i++)
{
if(row.getCell(i).getStringCellValue().trim().equals(colName.trim()))
col_Num = i;
}
row = sheet.getRow(rowNum - 1);
cell = row.getCell(col_Num);
if(cell.getCellType() == CellType.STRING)
return cell.getStringCellValue();
else if(cell.getCellType() == CellType.NUMERIC || cell.getCellType() == CellType.FORMULA)
{
String cellValue = String.valueOf(cell.getNumericCellValue());
if(HSSFDateUtil.isCellDateFormatted(cell))
{
DateFormat df = new SimpleDateFormat("dd/MM/yy");
Date date = cell.getDateCellValue();
cellValue = df.format(date);
}
return cellValue;
}else if(cell.getCellType() == CellType.BLANK)
return "";
else
return String.valueOf(cell.getBooleanCellValue());
}
catch(Exception e)
{
e.printStackTrace();
return "row "+rowNum+" or column "+colNum +" does not exist in Excel";
}
}
}
Above code is giving me an error saying:
Incompatible operand types int and CellType
Initially I used cell.getCellTypeEnum() method instead of cell.getCellType(). But cell.getCellTypeEnum() gave me error saying, The method getCellTypeEnum() is undefined for the type XSSFCell
How can i fix this issue?
Thanks in advance.

Error while using TestNg DataProvider must return either Object[][] or Iterator<Object>[], not class [[Ljava.lang.Object;

Testcase:
package Test;
import org.testng.annotations.AfterTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import Page.LoginPage;
import Utility.TestDataProvider;
import Utility.TestUtil;
//Testcase to perform login
public class LoginTest {
LoginPage page=new LoginPage();
#Test(dataProvider="ExcelDataProvider",dataProviderClass=TestDataProvider.class)
public void Logintest(String username,String password){
//page.login("user#phptravels.com","demouser");
page.login(username,password);
}
#AfterTest
public void TearDown(){
TestUtil.quit();
}
}
DataProvider:
package Utility;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
public class TestDataProvider {
static ExcelReader reader=new ExcelReader();
#DataProvider(name="ExcelDataProvider")
public static Object[][] ExcelDataProvider()
{
Object [][] rest = reader.readDataExcel("UserLogin");
return rest;
}
}
ExcelReader:
package Utility;
import java.io.File;
import java.io.FileInputStream;
import java.util.List;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFTable;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelReader {
static String fileName="Testdata";
public Object[][] readDataExcel(String TableName){
String filePath="F:\\TravelSite\\TravelSiteAutomation\\Testdata.xlsx";
File file =new File(filePath);
try{
FileInputStream stream=new FileInputStream(file);
Workbook workbook = new XSSFWorkbook(stream);
XSSFSheet sheet=(XSSFSheet) workbook.getSheet("UnitTest");
List<XSSFTable> tables = sheet.getTables();
for(XSSFTable table:tables){
String name=table.getName();
if(name.equals(TableName)){
int ci=0,cj=0;
int rowNum=sheet.getLastRowNum()-sheet.getFirstRowNum();
//System.out.println(rowNum);
String[][] dataArray=new String[rowNum][100];
for(int i = 1; i < rowNum+1; i++) {
Row row = sheet.getRow(i);
//Create a loop to print cell values in a row
int colNum=row.getLastCellNum();
// System.out.println(colNum);
for(int j = 0; j <colNum; j++) {
//Print excel data in console
Cell cell=row.getCell(j);
DataFormatter formatter = new DataFormatter();
String var_name = formatter.formatCellValue(cell);
System.out.print(var_name+" || ");
dataArray[ci][cj]=var_name;
}
System.out.println();
}
workbook.close();
return dataArray;
}
}
Log.info("Table name is incorrect");
return null;
}
catch(Exception e)
{
Log.debug(e.getMessage());
return null;
}
}
}
so when i try to run the testcase i get an error
org.testng.TestNGException:
Data Provider public static java.lang.Object[][]
Utility.TestDataProvider.ExcelDataProvider() must return either
Object[][] or Iterator[], not class [[Ljava.lang.Object;
Nothing seems to resolve it,POI version 3.15, TestNGversion 6.10
The problem is with the ExcelReader class. Please find below the fixed version of the same which should solve the problem
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFTable;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.util.ArrayList;
import java.util.List;
public class ExcelReader {
public static String[][] readDataExcel(String TableName) {
String filePath = "src/test/resources/Testdata.xlsx";
try {
Workbook workbook = new XSSFWorkbook(filePath);
XSSFSheet sheet = (XSSFSheet) workbook.getSheet("UnitTest");
List<XSSFTable> tables = sheet.getTables();
for (XSSFTable table : tables) {
String name = table.getName();
if (! name.equals(TableName)) {
continue;
}
int rowCount = sheet.getLastRowNum() - sheet.getFirstRowNum();
System.out.println(rowCount);
int columnCount = - 1;
List<List<String>> data = new ArrayList<>();
for (int i = 1; i < rowCount + 1; i++) {
Row row = sheet.getRow(i);
int colNum = row.getLastCellNum();
if (columnCount == - 1) {
columnCount = colNum;
}
List<String> rowData = new ArrayList<>();
for (int j = 0; j < colNum; j++) {
Cell cell = row.getCell(j);
DataFormatter formatter = new DataFormatter();
String var_name = formatter.formatCellValue(cell);
if (var_name != null && ! var_name.trim().isEmpty()) {
rowData.add(var_name);
}
}
if (! rowData.isEmpty()) {
data.add(rowData);
}
}
workbook.close();
String[][] dataArray = new String[rowCount-1][columnCount];
int rowIndex = 0;
for (List<String> row : data) {
int colIndex = 0;
for (String rowData : row) {
dataArray[rowIndex][colIndex++] = rowData;
}
rowIndex++;
}
return dataArray;
}
System.err.println("Table name is incorrect");
return new String[][] {{}};
} catch (Exception e) {
e.printStackTrace();
return new String[][] {{}};
}
}
}

Reading a 10 MB file in Apache POI

The project that I'm working on is trying to read a very large Excel file (a couple hundred columns and around 3000 rows) and recognize patterns in a series of letters. It works just fine on smaller files, but when I try to run it using this file I receive a java.lang.OutOfMemoryError: Java heap space error even when I'm only trying to analyze the first few rows. The error appears to be at Workbook wb = WorkbookFactory.create(new File(filepath));
I've tried a few of the solutions on this website, but have not come across any success. My code is as follows:
import java.awt.List;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
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 ExcelReader {
public int Reader(File file) throws IOException, EncryptedDocumentException, InvalidFormatException {
String filepath = file.getPath();
Workbook wb = WorkbookFactory.create(new File(filepath));
XSSFSheet sheet = (XSSFSheet) wb.getSheetAt(0);
XSSFRow row;
XSSFCell cell;
ArrayList<Integer> list = new ArrayList<Integer>();
int rows;
int cols = 0;
int temp = 0;
rows = sheet.getPhysicalNumberOfRows();
for (int i = 0; i <= 1; i++) {
row = sheet.getRow(i);
if (row != null) {
temp = sheet.getRow(i).getPhysicalNumberOfCells();
if (temp > cols)
cols = temp;
}
}
for (int r = 0; r <= 60; r++) {
row = sheet.getRow(r);
if (row != null) {
for (int c = 0; c <= cols; c++) {
int numblanks = 0;
cell = row.getCell((short) c);
if (cell != null) {
//System.out.print(cell + "\t\t");
} else {
//System.out.print("\t\t");
}
if (cell != null && cell.getCellType() == XSSFCell.CELL_TYPE_STRING) {
if ("N".equals(cell.getStringCellValue())) {
for (int k = c; k <= cols; k++) {
if ("-".equals(row.getCell(k).getStringCellValue())) {
numblanks++;
continue;
}
if ("S".equals(row.getCell(c + 2 + numblanks).getStringCellValue())
|| "T".equals(row.getCell(c + 2 + numblanks).getStringCellValue())) {
list.add((int) sheet.getRow(1).getCell(c).getNumericCellValue());
break;
}
}
}
}
}
System.out.println();
}
}
System.out.println();
System.out.println("Rows: " + rows);
System.out.println("Columns: " + cols);
System.out.println(list);
return temp;
}
}
Thank you for any help you can give me!
I solved this issue before. My case was to read a 23M Excel file which contains 230k rows.
Increase maximum heap size is not a good solution. Apache poi does not have a streaming mode to read data. This non-streaming mode costs too much memory.
My solution is to convert the data to xml and then use XMLReader to parse the data.
Please check the following sample code:
protected List<Entity> parseData(InputStream in) throws Exception {
OPCPackage pkg = OPCPackage.open(in);
XSSFReader r = new XSSFReader(pkg);
SharedStringsTable sst = r.getSharedStringsTable();
XMLReader parser = fetchSheetParser(sst);
XSSFReader.SheetIterator sheets = (XSSFReader.SheetIterator) r.getSheetsData();
while (sheets.hasNext()) {
InputStream sheet = sheets.next();
InputSource sheetSource = new InputSource(sheet);
parser.parse(sheetSource);
sheet.close();
break; // if only need to process one sheet.
}
return SheetHandler.getRawData();
}
private XMLReader fetchSheetParser(SharedStringsTable sst) throws SAXException {
XMLReader parser =
XMLReaderFactory.createXMLReader();
ContentHandler handler = new SheetHandler(sst);
parser.setContentHandler(handler);
return parser;
}
private static class SheetHandler extends DefaultHandler {
private SharedStringsTable sst;
private String lastContents;
private boolean nextIsString;
private boolean nextIsInlineString;
private boolean nextIsNull;
private SheetHandler(SharedStringsTable sst) {
this.sst = sst;
rawData = new ArrayList<Entity>();
}
public static List<Entity> getRawData() {
return rawData;
}
#Override
public void startElement(String uri, String localName, String name,
Attributes attributes) throws SAXException {
}
#Override
public void endElement(String uri, String localName, String name)
throws SAXException {
}
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
lastContents += new String(ch, start, length);
}
}
}

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 read values from an excel file using Apache POI

I am currently working on a project for my computer science class, and I was trying to figure out how to retrieve and print certain values from a file in excel. Such as, how would I go about printing the integer in column J, row 6?
Better yet, is there a way for me to return the row number of a string in column 1? Such as, if I had a string "Phone" in column 1, could I use a command to return the row number of the first instance of "phone"?
I have looked at other questions, none of which sufficiently answered my own.
Here you go refer to this class file for iterating over an excel file
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.util.Iterator;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DataFormatter;
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 Test {
private static final String FILE_NAME = "/users/developer/Documents/myFile.xlsx";
public void employeesUpload() {
String fName = "";
String lName = "";
String phoneNumber = "";
String email = "";
String gender = "";
String employeeCode = "";
try {
FileInputStream excelFile = new FileInputStream(new File(FILE_NAME));
Workbook workbook = new XSSFWorkbook(excelFile);
Sheet datatypeSheet = workbook.getSheetAt(0);
Iterator<Row> iterator = datatypeSheet.iterator();
int rowIndex = 0;
DataFormatter formatter = new DataFormatter();
while (iterator.hasNext()) {
Row currentRow = iterator.next();
if (rowIndex > 0) {
Iterator<Cell> cellIterator = currentRow.iterator();
employeeCode = fName = lName = phoneNumber = email = gender = "";
int cellIndex = 0;
while (cellIndex <= 5) {
Cell currentCell = currentRow.getCell(cellIndex);
if (cellIndex == 4) {
employeeCode = formatter.formatCellValue(currentCell).trim();
}
if (cellIndex == 1) {
fName = formatter.formatCellValue(currentCell).trim();
}
if (cellIndex == 2) {
lName = formatter.formatCellValue(currentCell).trim();
}
if (cellIndex == 0) {
email = formatter.formatCellValue(currentCell);
email = email.trim().toLowerCase();
}
if (cellIndex == 3) {
phoneNumber = formatter.formatCellValue(currentCell).trim();
}
cellIndex++;
}
Cell resultCell = currentRow.getCell(7);
if (resultCell == null) {
resultCell = currentRow.createCell(7);
}
Cell employementIdCell = currentRow.getCell(8);
if (employementIdCell == null) {
employementIdCell = currentRow.createCell(8);
}
if (true) {
resultCell.setCellType(Cell.CELL_TYPE_STRING);
employementIdCell.setCellValue("Success");
resultCell.setCellValue(email);
} else {
resultCell.setCellType(Cell.CELL_TYPE_STRING);
resultCell.setCellValue("Error");
}
}
rowIndex++;
}
FileOutputStream outputStream = new FileOutputStream(FILE_NAME);
workbook.write(outputStream);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws ParseException, UnsupportedEncodingException {
Test employeesBulkUpload = new Test();
employeesBulkUpload.employeesUpload();
}
}
Hope this helps :)
user https://github.com/jueyue/easypoi this jar
use annotion to easy read excel
public class ExcelImportNewDateTest {
#Test
public void importTest() {
ImportParams params = new ImportParams();
params.setTitleRows(1);
params.setHeadRows(1);
long start = new Date().getTime();
List<NewDateEntity> list = ExcelImportUtil.importExcel(
new File(FileUtilTest.getWebRootPath("import/ExcelNewDateTest.xlsx")), NewDateEntity.class, params);
System.out.println(new Date().getTime() - start);
Assert.assertEquals(list.size(), 100);
System.out.println(list.size());
System.out.println(ReflectionToStringBuilder.toString(list.get(1)));
}
}

Categories

Resources