Evaluate all formula cells in cell - java Apache poi - java

I am currently using
XSSFFormulaEvaluator.evaluateAllFormulaCells(wb);
However, this leaves formula in the cell.
I read similar questions to remove the formula from cell and keep only value using
evaluator.evaluateInCell(cell);
How can I use evaluateInCell with all formula cells?
One way would be to loop over all cells, is there any other way?
I want to achieve a sheet without any formulas having just calculated values

See the Snipet here. For more Details
// existing Workbook setup
FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
// existing Sheet, Row, and Cell setup
if (cell.getCellType() == CellType.FORMULA) {
switch (evaluator.evaluateFormulaCell(cell)) {
case BOOLEAN:
System.out.println(cell.getBooleanCellValue());
break;
case NUMERIC:
System.out.println(cell.getNumericCellValue());
break;
case STRING:
System.out.println(cell.getStringCellValue());
break;
}
}

Related

How to dump my data from excel sheet to Mongodb with Java [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I just need to read my excel file, which will be containing n no. of columns, and push those data into my MongoDB with Java programming.
Have you considered using Apache POI for spreadsheets? They have various examples on how to read/write Excel files, for instance:
// Get content of cells
// import org.apache.poi.ss.usermodel.*;
Sheet sheet1 = wb.getSheetAt(0);
for (Row row : sheet1) {
for (Cell cell : row) {
CellReference cellRef = new CellReference(row.getRowNum(), cell.getColumnIndex());
System.out.print(cellRef.formatAsString());
System.out.print(" - ");
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
System.out.println(cell.getRichStringCellValue().getString());
break;
case Cell.CELL_TYPE_NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
System.out.println(cell.getDateCellValue());
} else {
System.out.println(cell.getNumericCellValue());
}
break;
case Cell.CELL_TYPE_BOOLEAN:
System.out.println(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_FORMULA:
System.out.println(cell.getCellFormula());
break;
default:
System.out.println();
}
}
}
Then, for mapping the contents to MongoDB you would have to use the Java driver. I couldn't give you much information on that as I've only ever used the Python driver, but the introductory manual seems quite easy to follow.

Get cell by its content

Is there a way to get the cell object or coordinate by the data the cell contains?
For example if the cell with coordinates (1;5) contains the string "FINDME", i'd like to do something like Workbook.GetCellByData("FINDME") and it should return the Cell object or (1;5).
I have found a code snippet on the Apache POI website that could be useful. I could just read the whole workbook and find the data with an IF-statement, but that's kind of dirty...
EDIT:
I have coded the "dirty" solution as follows:
public Cell getCellByContent(String data) {
for (Row row : wb.getSheetAt(0)) {
for (Cell cell : row) {
if (cell.getCellType() == Cell.CELL_TYPE_STRING){
System.out.println(String.format("Found String type at (%s,%s) and read: %s", row.getRowNum(), cell.getColumnIndex(), cell.getStringCellValue()));
if (cell.getStringCellValue() == data) { //HERE
return cell; //HERE
} //HERE
}
}
}
System.out.println("Can't find it bruh!");
return null;
For some reason it fails at the if-statement. Id like to get the Cell with the content "%title%".
Output:
Found String type at (0,0) and read: %title% <------ IT'S RIGHT HERE!
Found String type at (2,0) and read: Test Information
...
Can't find it bruh!
Does someone have an idea why this is not working?
To fix the dirty solution replace
if (cell.getStringCellValue() == data)
with
if (cell.getStringCellValue().equals(data))
I think I can help you. you just make two for() loops for rows and columns and then type Workbook.getCellValue(i,j) (i is the number of the row and j is the number of the column

POI says Cell is empty but cell has a value

I'm opening a Excel (xls) file in my Java Application with POI.
There are 30 Lines in this Excelfile.
I need to get the Value at ColumnIndex 9.
My code:
Workbook wb;
wb = WorkbookFactory.create(inp);
Sheet sheet = wb.getSheetAt(0);
for (Row row : sheet) {
if (row.getLastCellNum() >= 6) {
for (Cell cell : row) {
if(cell.getColumnIndex == 9) {
//do something
}
}
}
}
Every Row in Excel has Values in Columns 1-14.
My problem is, only some Values are recognized. I wrote the same value in every cell in ColumnIndex 9 (10th Column in my Excel sheet), but the Problem is still the same.
What could cause this problem?
Make sure you set the same Date format for all cells in column (select column and set format explicity) And i belive using DataUtil class to get data is more appropriate, than call cell.getDateCellValue().
POI uses 0 based counting for columns. So, if you want the 9th Column, you need to fetch the cell with index 8, not 9. It looks like you're checking for column with index 9, so are one column out.
If you're not sure about 0 based indexing, then the safest thing is to use the CellReference class to help you. This will translate between Excel style references, eg A1, and POI style 0-based offsets eg 0,0. Use something like:
CellReference ref = new CellReference("I10");
Row r = sheet.getRow(ref.getRow());
if (r == null) {
// That row is empty
} else {
Cell c = r.getCell(ref.getCol());
// c is now the cell at I10
}
Seems to be a Problem with the excel document(s).
Converting them to csv and then back to xls solves the problem.

Empty cells issue when extracting excel data using POI in JAVA?

I have just Extracted the cells from the excel sheet using Apache POI, everything is working fine. But whenever there is an empty cell, the very next right cell data is what I get as a output. But, if exists a value in the latter, the desired output is coming.
This is the logic I've written.
Iterator<Row> rowIterator=sheet.rowIterator();
while(rowIterator.hasNext())
{
ExtractedRowsString extRows=new ExtractedRowsString();
ArrayList<HSSFCell> list=new ArrayList<HSSFCell>();
HSSFRow row=(HSSFRow) rowIterator.next();
Iterator<Cell> cellIterator=row.cellIterator();
while(cellIterator.hasNext())
{
HSSFCell cell=(HSSFCell)cellIterator.next();
list.add(cell);
}
if(check)
{
addBean(list,extRows);
print(extRows);
}
check=true;
}
What may be the problem?
EDITED :
public static void addBean(ArrayList list,ExtractedRowsString extRows)
{
for(int i=0;i<list.size();i++)
{
switch(i)
{
case 0:
extRows.setSchool_success_id((list.get(i)).toString());
break;
case 1:
extRows.setPem_id( (list.get(i)).toString() );
break;
case 2:
extRows.setDistrict_code((list.get(i)).toString());
break;
case 3:
extRows.setDistrict((list.get(i)).toString());
break;
}
}
}
From the docs:
cellIterator
public java.util.Iterator cellIterator()
Specified by:
cellIterator in interface Row
Returns:
cell iterator of the physically
defined cells. Note that the 4th
element might well not be cell 4, as
the iterator will not return
un-defined (null) cells. Call
getCellNum() on the returned cells to
know which cell they are. As this only
ever works on physically defined
cells, the Row.MissingCellPolicy has
no effect.
In short, empty cells do not show up in the iterator so you always have to check which cell you got.
ArrayList does permit adding nulls. Also what is the addBean method doing (skipping nulls or empty strings perhaps?) Can you post a small working code that one can run ?

Java POI - anyone been able to extract numbers from formula cells?

I've been using Java POI for some time now, but have encountered a new problem, and I'm wondering if anyone has found a solution.
When you read a spreadsheet, you need to know the type of cell in order to use the proper read method.
So you get the cell type, then call the appropriate read method to get the cell's contents.
This works for all cells except for the FORMULA cell, where the value is a number. If it's text, you can read it just fine. But if the resulting value is a number, then all you get from the cell is a blank string.
I've been through the javadocs for POI, and am using the correct data type (HSSFRichTextString), but still no joy.
Anyone have a solution?
P.S. this behavior of POI does bug me as there should be a default cell.toString() method that would return the string representation of ANY cell type, say defaulting to the cell's value property. (sort of like the paste-special where you can choose "value").
PPS: As asked - I'm using Java 6 (1.6.0_06) and poi-3.0.2-FINAL-20080204.jar
FileInputStream fis = new FileInputStream("c:/temp/test.xls");
Workbook wb = new HSSFWorkbook(fis); //or new XSSFWorkbook("c:/temp/test.xls")
Sheet sheet = wb.getSheetAt(0);
FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
// suppose your formula is in B3
CellReference cellReference = new CellReference("B3");
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;
}
Copied shamelessly from here
Just convert that cell into text .. using copy-"paste special" ... I did it as follows ....
Read from Point # 2 at :
http://www.asif-shahzad.com/2010/12/how-to-read-numbers-as-string-value-in.html
If POI doesn't work out for you, try Andy Khan's JExcel. I prefer it.
An alternative to using createFormulaEvaluator is to use SetCellType(CellType.STRING) and then access StringCellValue. I ran into problems using a formula evaluator (using NPOI) when it contains the WORKDAY() function.

Categories

Resources