How to import Excel files in Java - java

Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/xmlbeans/XmlException
at NewClass.main(NewClass.java:18)
Caused by: java.lang.ClassNotFoundException: org.apache.xmlbeans.XmlException
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:641)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:188)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
... 1 more
C:\Users\Dell\AppData\Local\NetBeans\Cache\16\executor-snippets\run.xml:111: The following error occurred while executing this line:
C:\Users\Dell\AppData\Local\NetBeans\Cache\16\executor-snippets\run.xml:68: Java returned: 1
BUILD FAILED (total time: 0 seconds)
I am Getting This error and I don't know ho to resolve it now Here is my code :
//creating workbook instance that refers to .xls file
XSSFWorkbook wb = new XSSFWorkbook(fis);
//creting a sheet object to retrive the object
XSSFSheet sheet = wb.getSheetAt(0);
//evaluatingf cell type
FormulaEvaluator fmEval = wb.getCreationHelper().createFormulaEvaluator();
for(Row row:sheet){
for(Cell cell: row){
switch(fmEval.evaluateInCell(cell).getCellType()){
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();
}
}

Related

Apache POI - Not implemented error with CONCAT function

I'm trying to edit a excel document that contains formulas, the editing works fine but the formulas don't update.
I'm trying to use the following code to get it to evaluate the formulas, however i get an error
FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
for (Row r : sheet) {
for (Cell c : r) {
evaluator.evaluateFormulaCell(c);
}
}
Exception in thread "AWT-EventQueue-0" org.apache.poi.ss.formula.eval.NotImplementedException: Error evaluating cell Sheet1!C17
at org.apache.poi.ss.formula.WorkbookEvaluator.addExceptionInfo(WorkbookEvaluator.java:344)
at org.apache.poi.ss.formula.WorkbookEvaluator.evaluateAny(WorkbookEvaluator.java:285)
at org.apache.poi.ss.formula.WorkbookEvaluator.evaluate(WorkbookEvaluator.java:216)
at org.apache.poi.xssf.usermodel.BaseXSSFFormulaEvaluator.evaluateFormulaCellValue(BaseXSSFFormulaEvaluator.java:56)
at org.apache.poi.ss.formula.BaseFormulaEvaluator.evaluateFormulaCell(BaseFormulaEvaluator.java:185)
at Timetable.ExcelAPI.calculateFormula(ExcelAPI.java:139)
Cell C17 has the following formula.
=IF(C3="","",CONCAT($A17,$B17,C3,$B17,$A$16))
I've also tried
=IF(C3="","",CONCATENATE($A17,$B17,C3,$B17,$A$16))
If i programmatically create the formula it works
cell.setCellFormula("IF(C3=\"\",\"\",CONCAT($A17,$B17,C" + (start + 1) + ",$B17,$A$16))");
Since Excel function support of apache poi is at Excel 2007 standard, CONCATENATE is implemented but CONCAT is not. Furthermore functions which are introduced after Excel 2007 are prefixed with _xlfn..
So your full stacktrace should contain:
...
Caused by: org.apache.poi.ss.formula.eval.NotImplementedFunctionException: _xlfn.CONCAT
...
A work around could be replacing "_xlfn.CONCAT" by "CONCATENATE" in formulas before evaluating.
Following code works for me and evaluates CONCATENATE as well as CONCAT formulas.
import org.apache.poi.ss.usermodel.*;
import java.io.FileInputStream;
class ReadExcel {
public static void main(String[] args) throws Exception {
Workbook workbook = WorkbookFactory.create(new FileInputStream("./ExcelExampleConcatenate.xlsx"));
FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
DataFormatter dataFormatter = new DataFormatter();
Sheet sheet = workbook.getSheetAt(0);
for (Row row : sheet) {
for (Cell cell : row) {
if (cell.getCellType() == CellType.FORMULA && cell.getCellFormula().contains("_xlfn.CONCAT")) {
cell.setCellFormula(cell.getCellFormula().replace("_xlfn.CONCAT", "CONCATENATE"));
}
String value = dataFormatter.formatCellValue(cell, evaluator);
System.out.println(value);
}
}
workbook.close();
}
}
Good news - the CONCAT function is now supported! Bad news - not in your version...
If you upgrade (once available) to Apache POI 5.0.1 or later, the CONCAT function is now supported, see https://bz.apache.org/bugzilla/show_bug.cgi?id=65185
If you're impatient and want to backport the missing function, it's http://svn.apache.org/viewvc?view=revision&revision=1887656
Resolved it by changing the call to the function to simply
workbook.setForceFormulaRecalculation(true);

not able to evaluate nested formula in excel using apache poi java

Hi I am trying to Evaluate a cell value with Nested formula using
apache POI 4.1.0. When I am trying with Normal formula it works fine.
Conisder the below code:
FileInputStream inputExcelFile = new FileInputStream(new File(INPUT_FILE_NAME));
XSSFWorkbook workbook = new XSSFWorkbook(inputExcelFile);
XSSFSheet sheet = workbook.createSheet("Total");
Row row = sheet.createRow(0); Cell cell = row.createCell(0);
//setting formula in the cell
cell.setCellFormula("IF('Data Set'!B2=0,CONCATENATE(IF('Data Set'!J2="","UMS",'Data Set'!J2),"_",IF('Data Set'!K2<>"",'Data Set'!K2&"_",""),'Data Set'!H2),"");
Cell cellValue = formulaEvaluator.evaluateInCell(cell);
Now, if do cell.setCellFormula("CONCATENATE(F4,"/",G4)") or any direct formal this code works fine but when using nested formula like "IF(....,CONCATENATE(IF...))" it throws the below error
Exception in thread "main" org.apache.poi.ss.formula.eval.NotImplementedException: Error evaluating cell Total!A1
at org.apache.poi.ss.formula.WorkbookEvaluator.addExceptionInfo(WorkbookEvaluator.java:344)
at org.apache.poi.ss.formula.WorkbookEvaluator.evaluateAny(WorkbookEvaluator.java:285)
at org.apache.poi.ss.formula.WorkbookEvaluator.evaluate(WorkbookEvaluator.java:216)
at org.apache.poi.xssf.usermodel.BaseXSSFFormulaEvaluator.evaluateFormulaCellValue(BaseXSSFFormulaEvaluator.java:56)
at org.apache.poi.ss.formula.BaseFormulaEvaluator.evaluateInCell(BaseFormulaEvaluator.java:145)
at org.apache.poi.xssf.usermodel.XSSFFormulaEvaluator.evaluateInCell(XSSFFormulaEvaluator.java:85)
at org.apache.poi.xssf.usermodel.XSSFFormulaEvaluator.evaluateInCell(XSSFFormulaEvaluator.java:34)
at com.example.com.CollibraAutomationScript.evaluateFormula(CollibraAutomationScript.java:255)
at com.example.com.CollibraAutomationScript.main(CollibraAutomationScript.java:164)
Caused by: org.apache.poi.ss.formula.eval.NotImplementedException: Error evaluating cell 'Data Set'!B2
at org.apache.poi.ss.formula.WorkbookEvaluator.addExceptionInfo(WorkbookEvaluator.java:344)
at org.apache.poi.ss.formula.WorkbookEvaluator.evaluateAny(WorkbookEvaluator.java:285)
at org.apache.poi.ss.formula.WorkbookEvaluator.evaluateReference(WorkbookEvaluator.java:792)
at org.apache.poi.ss.formula.SheetRefEvaluator.getEvalForCell(SheetRefEvaluator.java:48)
at org.apache.poi.ss.formula.SheetRangeEvaluator.getEvalForCell(SheetRangeEvaluator.java:74)
at org.apache.poi.ss.formula.LazyRefEval.getInnerValueEval(LazyRefEval.java:39)
at org.apache.poi.ss.formula.eval.OperandResolver.chooseSingleElementFromRef(OperandResolver.java:217)
at org.apache.poi.ss.formula.eval.OperandResolver.getSingleValue(OperandResolver.java:67)
at org.apache.poi.ss.formula.eval.RelationalOperationEval.evaluate(RelationalOperationEval.java:66)
at org.apache.poi.ss.formula.functions.Fixed2ArgFunction.evaluate(Fixed2ArgFunction.java:33)
at org.apache.poi.ss.formula.OperationEvaluatorFactory.evaluate(OperationEvaluatorFactory.java:153)
at org.apache.poi.ss.formula.WorkbookEvaluator.evaluateFormula(WorkbookEvaluator.java:541)
at org.apache.poi.ss.formula.WorkbookEvaluator.evaluateAny(WorkbookEvaluator.java:275)
... 7 more
Caused by: org.apache.poi.ss.formula.eval.NotImplementedException: Error evaluating cell 'Data Set'!A2
at org.apache.poi.ss.formula.WorkbookEvaluator.addExceptionInfo(WorkbookEvaluator.java:344)
at org.apache.poi.ss.formula.WorkbookEvaluator.evaluateAny(WorkbookEvaluator.java:285)
at org.apache.poi.ss.formula.WorkbookEvaluator.evaluateReference(WorkbookEvaluator.java:792)
at org.apache.poi.ss.formula.SheetRefEvaluator.getEvalForCell(SheetRefEvaluator.java:48)
at org.apache.poi.ss.formula.SheetRangeEvaluator.getEvalForCell(SheetRangeEvaluator.java:74)
at org.apache.poi.ss.formula.LazyRefEval.getInnerValueEval(LazyRefEval.java:39)
at org.apache.poi.ss.formula.eval.OperandResolver.chooseSingleElementFromRef(OperandResolver.java:217)
at org.apache.poi.ss.formula.eval.OperandResolver.getSingleValue(OperandResolver.java:67)
at org.apache.poi.ss.formula.functions.Countif.evaluateCriteriaArg(Countif.java:498)
at org.apache.poi.ss.formula.functions.Countif.createCriteriaPredicate(Countif.java:470)
at org.apache.poi.ss.formula.functions.Countif.evaluate(Countif.java:442)
at org.apache.poi.ss.formula.functions.Fixed2ArgFunction.evaluate(Fixed2ArgFunction.java:33)
at org.apache.poi.ss.formula.OperationEvaluatorFactory.evaluate(OperationEvaluatorFactory.java:153)
at org.apache.poi.ss.formula.WorkbookEvaluator.evaluateFormula(WorkbookEvaluator.java:541)
at org.apache.poi.ss.formula.WorkbookEvaluator.evaluateAny(WorkbookEvaluator.java:275)
... 18 more
Caused by: org.apache.poi.ss.formula.eval.NotImplementedFunctionException: _xlfn.CONCAT
at org.apache.poi.ss.formula.UserDefinedFunction.evaluate(UserDefinedFunction.java:56)
at org.apache.poi.ss.formula.OperationEvaluatorFactory.evaluate(OperationEvaluatorFactory.java:155)
at org.apache.poi.ss.formula.WorkbookEvaluator.evaluateFormula(WorkbookEvaluator.java:541)
at org.apache.poi.ss.formula.WorkbookEvaluator.evaluateAny(WorkbookEvaluator.java:275)
... 31 more
So apache poi does not allow to exceute nested formula? because when i put this same formula in excel sheet its evaluating properly.

VLOOKUP_ADD_Array Apache POI

I'm using Apache POI to parse an excel document.
It works fine until I reach a cell whom has a VLOOKUP_ADD_ARRAY.
What my code does is:
XSSFWorkbook workbook = new XSSFWorkbook(httpOrder.getFile());
XSSFSheet sheet = workbook.getSheet("MySheet");
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_FORMULA:
CellValue value = workbook.getCreationHelper().createFormulaEvaluator().evaluateFormulaCell(cell)
break;
}
}
}
I'm getting the following error: org.apache.poi.ss.formula.FormulaParseException: Name 'VLOOKUP_ADD_ARRAY' is completely unknown in the current workbook
Can anyone help on this?
I assume VLOOKUP_ADD_ARRAY is a user defined function. It would help if you could post what is in the cell the error occurs for.
If it is indeed a user defined function, you have to reimplement it yourself. You can check this page for an example how to reimplement a user defined function.

Got null pointer exception when reading excel file

I am writing a function to read data from excel (.xls) then add it to a HashMap.
It work before but I get the error now.
I know why the error is raised: it is because of the sheet (Htest) that I want to read data is null.
I check my excel, there is the sheet with correct name of 'Htest'.
Also I check the number of sheet in workbook. It returns the correct number of sheets that the workbook has
I check the other sheet: It works.
It only throws error for a sheet that I am working on...
I dont know why the sheet is available in workbook but the code returns null??
I missed something?
Does anyone have the same problem? or can you give me a hint to work with it?
Thank you.
The error is:
Method arguments: org.testng.TestRunner#2f6d9d1c, "/enigma"
java.lang.NullPointerException
com.validant.enigma3.common.UIMap.readControls(UIMap.java:133)
com.validant.enigma3.common.UIMap.<init>(UIMap.java:32)
com.validant.enigma3.common.TestBase.beforeSuite(TestBase.java:24)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:606)
org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:84)
org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:564)
org.testng.internal.Invoker.invokeConfigurations(Invoker.java:213)
org.testng.internal.Invoker.invokeConfigurations(Invoker.java:138)
org.testng.SuiteRunner.privateRun(SuiteRunner.java:277)
org.testng.SuiteRunner.run(SuiteRunner.java:240)
org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
org.testng.TestNG.runSuitesSequentially(TestNG.java:1224)
org.testng.TestNG.runSuitesLocally(TestNG.java:1149)
org.testng.TestNG.run(TestNG.java:1057)
org.apache.maven.surefire.testng.TestNGExecutor.run(TestNGExecutor.java:74)
org.apache.maven.surefire.testng.TestNGXmlTestSuite.execute(TestNGXmlTestSuite.java:92)
org.apache.maven.surefire.Surefire.run(Surefire.java:180)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:606)
org.apache.maven.surefire.booter.SurefireBooter.runSuitesInProcess(SurefireBooter.java:350)
org.apache.maven.surefire.booter.SurefireBooter.main(SurefireBooter.java:1021)
The code is
private HashMap<String, MappingObj> readControls(String filepath, String sheetname)
throws IOException {
HashMap<String, MappingObj> controllist = new HashMap<String, MappingObj>();
//System.out.println("FILE PATH = " + filepath);
//System.out.println("SHEET NAME = " + sheetname);
FileInputStream file = new FileInputStream(filepath);
System.out.println(file.toString());
//Get the workbook instance for XLS file
HSSFWorkbook myWorkBook = new HSSFWorkbook(file);
//System.out.println("NUMBER of SHEET= "+myWorkBook.getNumberOfSheets());
HSSFSheet mySheet= myWorkBook.getSheet(sheetname);
if (myWorkBook.getSheet(sheetname)==null)
System.out.println("null");
Iterator<Row> rowIter = mySheet.rowIterator();
rowIter.next();
String[] arow = new String[3];
while (rowIter.hasNext()) {
HSSFRow row = (HSSFRow) rowIter.next();
Iterator<Cell> cells = row.cellIterator();
int i = 0;
// Check data from current cell, there is data on next cell or
// not?
while (cells.hasNext()) {
HSSFCell cell = (HSSFCell) cells.next();
arow[i] = cell.getStringCellValue().trim();
i++;
}
MappingObj mapObj = new MappingObj();
mapObj.setCodeName(arow[0]);
mapObj.setSelector(arow[1]);
mapObj.setPath(arow[2]);
controllist.put(arow[0], mapObj);
file.close();
}
return controllist;
}
The excel is:
I have 5 sheets in the excel with the order:
Login FileUpload SimpleTasks Htest Reference
All sheets have the same data schema (there are 3 columns: Control name, Selector, Path)
Just different datafor each column.
The sheet cause error is Htest and its data is
Control Name Selector Path
test1 cssSelector test2
You've said in the comments that the line giving the NPE is:
Iterator<Row> rowIter = mySheet.rowIterator();
Your problem is that you're not checking if the sheet you tried to fetch really existed. If you try to fetch a sheet with an invalid name, you'll get back null. From the Workbook JavaDocs:
Returns: Sheet with the name provided or null if it does not exist
So, your code should then be something more like:
HSSFSheet mySheet= myWorkBook.getSheet(sheetname);
if (mySheet == null) {
throw new IllegalArgumentException("No sheet exists with name " + sheetName);
}
Alternately, return null from your code there, and check for that in your calling code (rather than catching the exception).
If you're not sure what Sheets your Workbook really has (which might not be what you thought in the odd case), try:
for (int sn=0; sn < myWorkBook.getNumberOfSheets(); sn++) {
System.out.println("Sheet " + sn + " is called " + myWorkBook.getSheetName(sn));
}

Java POI : How to read Excel cell value and not the formula computing it?

I am using Apache POI API to getting values from an Excel file.
Everything is working great except with cells containing formulas. In fact, the cell.getStringCellValue() is returning the formula used in the cell and not the value of the cell.
I tried to use evaluateFormulaCell() method but it's not working because I am using GETPIVOTDATA Excel formula and this formula is not implemented in the API:
Exception in thread "main" org.apache.poi.ss.formula.eval.NotImplementedException: Error evaluating cell Landscape!K11
at org.apache.poi.ss.formula.WorkbookEvaluator.addExceptionInfo(WorkbookEvaluator.java:321)
at org.apache.poi.ss.formula.WorkbookEvaluator.evaluateAny(WorkbookEvaluator.java:288)
at org.apache.poi.ss.formula.WorkbookEvaluator.evaluate(WorkbookEvaluator.java:221)
at org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator.evaluateFormulaCellValue(HSSFFormulaEvaluator.java:320)
at org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator.evaluateFormulaCell(HSSFFormulaEvaluator.java:213)
at fromExcelToJava.ExcelSheetReader.unAutreTest(ExcelSheetReader.java:193)
at fromExcelToJava.ExcelSheetReader.main(ExcelSheetReader.java:224)
Caused by: org.apache.poi.ss.formula.eval.NotImplementedException: GETPIVOTDATA
at org.apache.poi.hssf.record.formula.functions.NotImplementedFunction.evaluate(NotImplementedFunction.java:42)
For formula cells, excel stores two things. One is the Formula itself, the other is the "cached" value (the last value that the forumla was evaluated as)
If you want to get the last cached value (which may no longer be correct, but as long as Excel saved the file and you haven't changed it it should be), you'll want something like:
for(Cell cell : row) {
if(cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
System.out.println("Formula is " + cell.getCellFormula());
switch(cell.getCachedFormulaResultType()) {
case Cell.CELL_TYPE_NUMERIC:
System.out.println("Last evaluated as: " + cell.getNumericCellValue());
break;
case Cell.CELL_TYPE_STRING:
System.out.println("Last evaluated as \"" + cell.getRichStringCellValue() + "\"");
break;
}
}
}
Previously posted solutions did not work for me. cell.getRawValue() returned the same formula as stated in the cell. The following function worked for me:
public void readFormula() throws IOException {
FileInputStream fis = new FileInputStream("Path of your file");
Workbook wb = new XSSFWorkbook(fis);
Sheet sheet = wb.getSheetAt(0);
FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
CellReference cellReference = new CellReference("C2"); // pass the cell which contains the formula
Row row = sheet.getRow(cellReference.getRow());
Cell cell = row.getCell(cellReference.getCol());
CellValue cellValue = evaluator.evaluate(cell);
switch (cellValue.getCellType()) {
case Cell.CELL_TYPE_BOOLEAN:
System.out.println(cellValue.getBooleanValue());
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.println(cellValue.getNumberValue());
break;
case Cell.CELL_TYPE_STRING:
System.out.println(cellValue.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;
}
}
There is an alternative command where you can get the raw value of a cell where formula is put on. It's returns type is String. Use:
cell.getRawValue();
If the need is to read values from Excel sheets and having them as strings then, for example to present them somewhere or to use them in text file formats, then using DataFormatter will be the best.
DataFormatter is able to get a string from each cell value, whether the cell value itself is string, boolean, number, error or date. This string then looks the same as Excel will show it in the cells in it's GUI.
Only problem are formula cells. Up to apache poi 5.1.0 a FormulaEvaluator is needed to evaluate the formulas while using DataFormatter. This fails when apache poi is not able evaluating the formula. From 5.2.0 on the DataFormatter can be set to use cached values for formula cells. Then no formula evaluation is needed if Excel had evaluated the formulas before.
Complete example:
import org.apache.poi.ss.usermodel.*;
import java.io.FileInputStream;
class ReadExcel {
public static void main(String[] args) throws Exception {
Workbook workbook = WorkbookFactory.create(new FileInputStream("./ExcelExample.xlsx"));
// up to apache poi 5.1.0 a FormulaEvaluator is needed to evaluate the formulas while using DataFormatter
FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
DataFormatter dataFormatter = new DataFormatter(new java.util.Locale("en", "US"));
// from 5.2.0 on the DataFormatter can set to use cached values for formula cells
dataFormatter.setUseCachedValuesForFormulaCells(true);
Sheet sheet = workbook.getSheetAt(0);
for (Row row : sheet) {
for (Cell cell : row) {
//String value = dataFormatter.formatCellValue(cell, evaluator); // up to apache poi 5.1.0
String value = dataFormatter.formatCellValue(cell); // from apache poi 5.2.0 on
System.out.println(value);
}
}
workbook.close();
}
}
If you want to extract a raw-ish value from a HSSF cell, you can use something like this code fragment:
CellBase base = (CellBase) cell;
CellType cellType = cell.getCellType();
base.setCellType(CellType.STRING);
String result = cell.getStringCellValue();
base.setCellType(cellType);
At least for strings that are completely composed of digits (and automatically converted to numbers by Excel), this returns the original string (e.g. "12345") instead of a fractional value (e.g. "12345.0"). Note that setCellType is available in interface Cell(as of v. 4.1) but deprecated and announced to be eliminated in v 5.x, whereas this method is still available in class CellBase. Obviously, it would be nicer either to have getRawValue in the Cell interface or at least to be able use getStringCellValue on non STRING cell types. Unfortunately, all replacements of setCellType mentioned in the description won't cover this use case (maybe a member of the POI dev team reads this answer).
SelThroughJava's answer was very helpful I had to modify a bit to my code to be worked .
I used https://mvnrepository.com/artifact/org.apache.poi/poi and https://mvnrepository.com/artifact/org.testng/testng as dependencies .
Full code is given below with exact imports.
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.util.CellReference;
import org.apache.poi.sl.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.CellValue;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ReadExcelFormulaValue {
private static final CellType NUMERIC = null;
public static void main(String[] args) {
try {
readFormula();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void readFormula() throws IOException {
FileInputStream fis = new FileInputStream("C:eclipse-workspace\\sam-webdbriver-diaries\\resources\\tUser_WS.xls");
org.apache.poi.ss.usermodel.Workbook workbook = WorkbookFactory.create(fis);
org.apache.poi.ss.usermodel.Sheet sheet = workbook.getSheetAt(0);
FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
CellReference cellReference = new CellReference("G2"); // pass the cell which contains the formula
Row row = sheet.getRow(cellReference.getRow());
Cell cell = row.getCell(cellReference.getCol());
CellValue cellValue = evaluator.evaluate(cell);
System.out.println("Cell type month is "+cellValue.getCellTypeEnum());
System.out.println("getNumberValue month is "+cellValue.getNumberValue());
// System.out.println("getStringValue "+cellValue.getStringValue());
cellReference = new CellReference("H2"); // pass the cell which contains the formula
row = sheet.getRow(cellReference.getRow());
cell = row.getCell(cellReference.getCol());
cellValue = evaluator.evaluate(cell);
System.out.println("getNumberValue DAY is "+cellValue.getNumberValue());
}
}

Categories