Error in using getRichStringCellValue() of Apache POI - java

The following is my java code for reading a excel sheet content.
String urlcnt="";
for (Row row : sheet) {
{
Cell firstCell = row.getCell(0);
urlcnt=firstCell.getRichStringCellValue();}
While compiling the above code am getting the following error.
ReadExcel.java:18: incompatible types
found : org.apache.poi.ss.usermodel.RichTextString required: java.lang.String
urlcnt=firstCell.getRichStringCellValue();//This line is the cause for the error
Instead of storing the getRichStringCellValue() in a string, if I just print the value of the cell, it works fine. But I go ahead and store it in a string for further processing the problem occurs.
Kindly let me know what has to be done to proceeed.

The error is because getRichStringCellValue() returns a HSSFRichTextString or XSSFRichTextString (depending on whether your cell is HSSFCell or XSSFCell) and you are assigning it to a String
Depending on your further processing -
Do you want to call applyFont or clearFormatting on the HSSFRichTextString ?
then store it in a HSSFRichTextString/XSSFRichTextString.
If you actually want only the String text, use the getString() method from the POI API
UPDATE as per your comments
Use it as
urlcnt=firstCell.getRichStringCellValue().getString();

Related

Apache poi getCell() returns wrong value

So im trying to recive cell value like '150symbols150symbols150symbols150symbols150symbols150symbols150symbols150symbols150symbols150symbols150symbols150symbols150symbols150symbols150symbol'
In some cases ill get correct (150...) value and in some reciving '78.0'. At first i thouth that i got wrong cell type in my .xls but after some work i found that they are the same. Also calling method getCellType returns me '1' and that is CELL_TYPE_STRING.
In the end its working something like this:
String value1 = getCellValue(row.getCell(0)); --150... correct value
String value2 = getCellValue(row.getCell(1)); --150... correct value
String value3 = getCellValue(row.getCell(2)); --78.0 incorrect value
private String getCellValue(Cell cell) {
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING: //similar for other cell types
//getting cell value based on its type
}
}
looking for some advices and tips cause im running out of ideas, maby im missing something?
thats how my excel looks :
enter image description here
p.s. there are many '150...' vals just for testing
You are using getCell(int var1) to get the content in a cell. But it returns the object of Cell class. You should use methods in Cell class to get values in Excel cells. There are methods like
getDateCellValue()
getNumericCellValue()
getStringCellValue()
to get the cell content depending on the CellType. Using CellType, you can decide how to get the cell content.
UPDATE:
If the problem still exists, check the data type of the cell from;
And do the necessary changes in the code to get the correct value.
Small tip: Also you can add a single quote ' at the beginning of the cell content. Then Apache POI will get the cell content as a String. The ' will not become a part of the cell content.

Apache POI cannot recognize sheet name: Specified named range 'RtSummary.1' does not exist in the current workbook

I am generating Excel file by java. I need to reference "summary" sheet in "overview" sheet. First, I declare the summary sheet name as "RtSummary.1-PLAN1". Then I worked on cells in overview sheet. However, I got error saying:
Exception in thread "main" org.apache.poi.ss.formula.FormulaParseException: Specified named range 'RtSummary.1' does not exist in the current workbook.
I print out the sheet name. It prints exactly what I expect. (It prints "RtSummary.1-PLAN1" instead of "RtSummary.1").
Then I tried to change the sheet name from "RtSummary.1-PLAN1" to "test". I didn't get such error any more.
I am confused what's wrong with my sheet name to cause such error. My code is as below:
//cell 3 (total orders) will be filled later
String summarySheetName="RtSummary."+snapshots[i].trim()+Integer.toString(i+1);
String detailSheetName="RtDetail."+snapshots[i]+(i+1);
Row orderRow;
//first comparison table content
int rowOffset=15+snapshots.length;
curRow=overviewSheet.createRow(rowOffset+i);
orderRow=curRow;
curCell=curRow.createCell(1);
curCell.setCellStyle(lrBarStyle);
curCell.setCellValue(snapshots[i]);
curCell=curRow.createCell(2);
curCell.setCellStyle(lrBarStyle);
if(sameDay)
curCell.setCellValue(dateSDF.format(startDate.getTime()));
else
curCell.setCellValue(dateSDF.format(startDate.getTime())+"-"+dateSDF.format(endDate.getTime()));
curCell=curRow.createCell(4);
curCell.setCellStyle(lrBarStyle);
System.out.println(summarySheetName);
curCell.setCellFormula(summarySheetName+"!N"+(routes.length+2));
System.out.println("0k");

generate excel sheet using Apache poi with Email Validation

I am generating excel sheet using apache poi for email --that means after generating excel if user enter email in the cell i need to validate that email
below is my code
DVConstraint EmailConstraint=null;
DataValidation EmaildataValidation =null;
EmailConstraint=DVConstraint.createCustomFormulaConstraint("AND(FIND("+'#'+",$A$2),FIND(.,$A$2),ISERROR(FIND( ,$A$2)))");---->getting error here only
EmaildataValidation =dataValidationHelper.createValidation(EmailConstraint, addressList1);
EmaildataValidation.setSuppressDropDownArrow(false);
sheet.addValidationData(EmaildataValidation);
when i execute this method i am getting following error
Stacktrace:] with root cause
org.apache.poi.ss.formula.FormulaParseException: Parse error near char 9 '#' in specified formula 'AND(FIND(#,$A$2),FIND(.,$A$2),ISERROR(FIND( ,$A$2)))'. Expected cell ref or constant literal
at org.apache.poi.ss.formula.FormulaParser.expected(FormulaParser.java:188)
at org.apache.poi.ss.formula.FormulaParser.parseSimpleFactor(FormulaParser.java:1128)
at org.apache.poi.ss.formula.FormulaParser.percentFactor(FormulaParser.java:1083)
at org.apache.poi.ss.formula.FormulaParser.powerFactor(FormulaParser.java:1070)
at org.apache.poi.ss.formula.FormulaParser.Term(FormulaParser.java:1430)
at org.apache.poi.ss.formula.FormulaParser.additiveExpression(FormulaParser.java:1530)
at org.apache.poi.ss.formula.FormulaParser.concatExpression(FormulaParser.java:1514)
at org.apache.poi.ss.formula.FormulaParser.comparisonExpression(FormulaParser.java:1471)
at org.apache.poi.ss.formula.FormulaParser.Arguments(FormulaParser.java:1056)
at org.apache.poi.ss.formula.FormulaParser.function(FormulaParser.java:943)
at org.apache.poi.ss.formula.FormulaParser.parseNonRange(FormulaParser.java:536)
at org.apache.poi.ss.formula.FormulaParser.parseRangeable(FormulaParser.java:416)
at org.apache.poi.ss.formula.FormulaParser.parseRangeExpression(FormulaParser.java:237)
at org.apache.poi.ss.formula.FormulaParser.parseSimpleFactor(FormulaParser.java:1123)
at org.apache.poi.ss.formula.FormulaParser.percentFactor(FormulaParser.java:1083)
at org.apache.poi.ss.formula.FormulaParser.powerFactor(FormulaParser.java:1070)
at org.apache.poi.ss.formula.FormulaParser.Term(FormulaParser.java:1430)
at org.apache.poi.ss.formula.FormulaParser.additiveExpression(FormulaParser.java:1530)
at org.apache.poi.ss.formula.FormulaParser.concatExpression(FormulaParser.java:1514)
at org.apache.poi.ss.formula.FormulaParser.comparisonExpression(FormulaParser.java:1471)
at org.apache.poi.ss.formula.FormulaParser.Arguments(FormulaParser.java:1056)
at org.apache.poi.ss.formula.FormulaParser.function(FormulaParser.java:943)
at org.apache.poi.ss.formula.FormulaParser.parseNonRange(FormulaParser.java:536)
at org.apache.poi.ss.formula.FormulaParser.parseRangeable(FormulaParser.java:416)
at org.apache.poi.ss.formula.FormulaParser.parseRangeExpression(FormulaParser.java:237)
at org.apache.poi.ss.formula.FormulaParser.parseSimpleFactor(FormulaParser.java:1123)
at org.apache.poi.ss.formula.FormulaParser.percentFactor(FormulaParser.java:1083)
at org.apache.poi.ss.formula.FormulaParser.powerFactor(FormulaParser.java:1070)
I tried a lot but not able do it.
First parameter to find function is string hence it must be quoted.
Find("#",..
In java you can use escape string character in between formula.

Poi ' characted seem to be added automatically

I use POI 3.1 to generate a xlsx file.
This character ' is added automcally in my cell
cell = row.createCell(0);
cell.setCellValue(atm.getEnvelop());
cell = row.createCell(1);
cell.setCellType(Cell.CELL_TYPE_NUMERIC);
cell.setCellValue(atm.getAmount().replace(".", ","));
atm.getEnvelop() and atm.getAmount() are string
atm.getEnvelop() value is 8635 but when i check in the file generated i get:' 8635
same thing for the other one
value is 200,00 i get '200,00
any idea?
Your problem is that you're calling cell.setCellValue(String), which automatically sets the cell type to be a string
If you want to set a numeric cell type (so there's no ' prefixed in Excel), you need to give Apache POI a number not a string.
This code will set '200.00 in Excel:
String s200 = "200.00";
cell.setCellValue(s200);
While this one will give you 200.00 in Excel:
// Once per workbook - tell excel to format with with two decimal points
DataFormat fmt = wb.createDataFormat()
CellStyle cs = wb.createCellStyle();
cs.setDataFormat(fmt.getFormat("0.00"));
// Once per cell
double d200 = 200.0;
cell.setCellValue(d200);
cell.setCellStyle(cs);
For your case, where your number seems to be coming in as a String, you'll need to parser it into a number (eg double) before giving it to POI
AT the place of cell.setCellType(Cell.CELL_TYPE_NUMERIC);
Use cell.setCellType(CELL_TYPE_STRING);
Because putting char '' is excel property for numeric value.
it could help you.
I am not sure but I am guessing you are trying to get an integer from a cell of Cell.Cell_TYPE_STRING. Try to get the amount from cell by calling this : cell.getNumericCellValue()

POI reading excel strings as numeric

I am using Apache POI for reading excel file. And while reading it I have noticed that it takes strings as float values.
If my cell contains 1 then it will fetch it as 1.0
I took some hints from previous questions here and modified the code but still the float representation remains as it is.
How would I read correctly the data for strings and dates?
DataFormatter df = new DataFormatter();
for (Row row : sheet) {
for(int cn=0; cn<row.getLastCellNum(); cn++) {
// If the cell is missing from the file, generate a blank one
// (Works by specifying a MissingCellPolicy)
Cell cell = row.getCell(cn, Row.CREATE_NULL_AS_BLANK);
// Print the cell for debugging
cell.setCellType(Cell.CELL_TYPE_STRING);
System.out.println("CELL: " + cn + " --> " + df.formatCellValue(cell));
if (row.getRowNum() == 0) {
sheetColumnNames.add(cell.getRichStringCellValue().getString());
}
}
}
Promoting a comment to an answer
The problem is the call
cell.setCellType(Cell.CELL_TYPE_STRING);
What that is doing is asking POI to try to convert the cell from whatever it is currently (eg a number) into a string. The conversion applied to try to do this is a fairly simple one, which is why you're loosing the formatting
If you just want to get back a String that contains the Cell Value as shown in Excel, just call DataFormatter directly, and it'll do its best. Playing around with the Cell Type will only confuse things, and will risk loosing formatting
Adding to above answer, poi will give you 1.0 as output even when you are using dataformatter class if you are trying to execute program against LIBRE OFFICE spreadsheet. As poi does not work in similar fashion with LIBRE SPREADSHEETS as it with excel.

Categories