Apache POI getStringCellValue() printing null - java

I'm getting a weird error while trying to read the Cell values through Apache POI in java:
System.out.println(row.getCell(13, Row.CREATE_NULL_AS_BLANK).getStringCellValue())
is always printing null, even after specifying the Missing policy as Row.CREATE_NULL_AS_BLANK.My writing logic to the Cell is :
public void writeCell( String value, Sheet sheet, int rowNum, int colNum)
{
Row row = sheet.getRow(rowNum);
if (row == null)
{
row = sheet.createRow(rowNum);
}
Cell cell = row.createCell(colNum, Cell.CELL_TYPE_STRING);
if (value == null)
{
return;
}
cell.setCellValue(value);
}
When I'm writing to Cell at colNum = 13 , the String value object is null. I'm not able to sort out this issue.

This line doesn't do what you seem to think it does:
System.out.println(row.getCell(13, Row.CREATE_NULL_AS_BLANK).getStringCellValue())
In effect, that's doing
Cell cell = row.getCell(13);
if (cell == null) { cell = row.createCell(13, Cell.CELL_TYPE_BLANK); }
So, if there is nothing in that cell, it creates it as an empty blank one
Then, you try doing:
cell.getStringCellValue()
This only works for String cells, and in the missing case you've told POI to give you a Blank new cell!
If you really just want a string value of a cell, use DataFormatter.formatCellValue(Cell) - that returns a String representation of your cell including formatting. Otherwise, check the type of your cell before trying to fetch the value!

The getStringCellValue() on the Cell interface would return "" if your code worked as supposed (setting the call blank).
Is it not possible that value for col id 13 is not null but "null"?

Related

how to get the next cell in the same row when using poi

I am using poi(v4.0.0) to import the excel document. But when I tried to get the next cell carModelCell, it always return null, this is my Java 8 code looks like:
public void verifyCar(Cell cell, int relativeRowIndex, Head head) {
if (cell.getRowIndex() > 0 && head.getFieldName().equals("car")) {
if (StringUtils.isBlank(cell.getStringCellValue())|| cell.getStringCellValue().equals("无车")) {
return;
}
Cell carModelCell = cell.getRow().getCell(cell.getColumnIndex() + 1);
if (carModelCell == null || StringUtils.isBlank(carModelCell.getStringCellValue())) {
SparkUserParseResult result = new SparkUserParseResult();
result.setSuccess(false);
UploadSparkUserDataListener.parseSuccess.set(result);
return;
}
}
}
I am tried to get row from Cell, and get the next cell value with the same row and do some check, but the next cell carModelCell always return null. I have already sure the next cell of current row have a value. why would this happen? what should I do to fix this problem? This code block was in CellStyleWriteHandler which extend AbstractCellStyleStrategy in easy excel (version 2.2.11):
public class CellStyleWriteHandler extends AbstractCellStyleStrategy {
#Override
protected void setContentCellStyle(Cell cell, Head head, Integer relativeRowIndex) {
impl(cell, head, relativeRowIndex);
}
}
I tried to get the last index num was 14, the current column index number was 13. the total column of my imported excel was 24, seems the easy excel did not pass the full column, is it possible to fix this problem? How to get the next cell of current row?
i also user poi to parse excel, i think problem in this line:
Cell carModelCell = cell.getRow().getCell(cell.getColumnIndex() + 1);
code above is error, becase cell can get from row,like:
Cell cell = sheetColumnRow.getRow()
one raw can cantain many Cell,but you can not get complete row from Cell, Parse row Cell value can not reverse; wish help you;

How to replace a cell value - Apache POI

I am trying to replace a cell value using existing cell value from other sheets(in the same workbook)
My code:
public static void update_sheet(XSSFWorkbook w)
{
XSSFSheet sheet,sheet_overview;
sheet_overview = w.getSheetAt(0);
int lastRowNum,latest_partition_date;
latest_partition_date = 3;
XSSFRow row_old, row_new;
XSSFCell cell_old, cell_new;
for(int i=1;i<=10;i++)
{
sheet = w.getSheetAt(i);
lastRowNum = sheet.getLastRowNum();
row_old = sheet.getRow(lastRowNum);
cell_old = row_old.getCell(0); //getting cell value from a sheet
row_new = sheet_overview.getRow(latest_partition_date);
cell_new = row_new.getCell(5);
***cell_new.setCellValue(cell_old)***;//trying to overwrite cellvalue
latest_partition_date++;
}
}
The 'type' values I am trying to copy
7/10/2017
7/11/2017
7/12/2017
7/13/2017
2017-07-14
2017-07-15
Error
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method setCellValue(boolean) in the type XSSFCell is not applicable for the arguments (XSSFCell)
at Sample2.update_overview_sheet(Sample2.java:78)
at Sample2.main(Sample2.java:26)
Any help or suggestions is appreciated.
The problem is that getCell() returns a value of type Cell. You're not actually retrieving the value of that cell, but the cell object itself. In order to set the value with setCellValue you need to provide it a value, something that's a date, boolean, string, richtextstring, etc., one of the methods that's listed here in the apache POI documentation for Cell.

How to get data of the merged cell given a cell indexes in java?

I am having an excel file and i am using apache-poi to get data of the excel file so if i read any cell value then how to know if the cell is a merged cell and get the value of the merged cell
So i am trying to know weather a cell is a merged cell or not if it is a merged cell i will try to get value of first row and first colon value of merged cell and if it is not a merged cell then i will directly get data of the value
like
String var = String.valueOf(sheet.getRow(Row).getCell(Cell));
Two key methods you need:
Sheet.getMergedRegions()
CellRangeAddressBase.isInRange(row,column) (merged regions extend from this)
Your code would just be something like:
public CellRangeAddress getMergedRegionForCell(Cell c) {
Sheet s = c.getRow().getSheet();
for (CellRangeAddress mergedRegion : s.getMergedRegions()) {
if (mergedRegion.isInRange(c.getRowIndex(), c.getColumnIndex())) {
// This region contains the cell in question
return mergedRegion;
}
}
// Not in any
return null;
}
Then check if you get null back, if not read the first row and column of the region to know the top left cell of the region containing your cell of interest
You can use Sheet.getMergedRegions() to determine all ranges of merged cells. Then you can use CellRangeAddress.isInRange(row,column) on the returned ranges to check if the cell in question is a merged cell.
public boolean isMergedCell(int row, int column) {
for (CellRangeAddress range : sheet.getMergedRegions()) {
if (range.isInRange(row, column)) {
return true;
}
}
return false;
}
This is my code (Kotlin) about how to get excel cell data as string taking into account that cell may be merged. I use this code for loading excel data into database.
fun getCellStr(sheet: XSSFSheet, cell: Cell): String {
var res = ""
val formatter = DataFormatter()
var inRange = false
for (range in sheet.getMergedRegions()) {
if (range.isInRange(cell.rowIndex, cell.columnIndex)) {
for (rIndex in range.firstRow..range.lastRow) {
for (cIndex in range.firstColumn..range.lastColumn) {
res = "$res${formatter.formatCellValue(sheet.getRow(rIndex).getCell(cIndex))}"
}
}
inRange = true
}
}
if (!inRange) {
res = formatter.formatCellValue(cell)
}
return res.trim()
}

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.

Categories

Resources