且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何通过NPOI获取.xlsx中的单元格字符串

更新时间:2023-11-15 16:18:10

这是NPOI的烦人功能 - 你需要检查 CellType 查看您可以使用哪个 * CellValue 属性。如果 CellType 返回公式,那么你需要检查 CachedFormulaResultType property。



StringCellValue 属性仅在以下情况下有效单元格为空白,字符串或返回字符串的公式。



如果将单元格的值设置为 4 ,类型将是 Numeric ,这意味着你必须使用 NumericCellValue



如果您只想将格式化的值作为字符串,无论单元格的类型如何,您都可以在单元格上使用 ToString 方法。 br />


您还需要注意空单元格 - 默认情况下,NPOI会跳过 GetCell 方法中的任何空单元格,所以单元格2可能不是第二列。为避免这种情况,您需要将 MissingCellPolicy.RETURN_NULL_AND_BLANK 传递给 GetCell 方法。



  string   value  = sheet.GetRow ( 2 )。GetCell( 3 ,MissingCellPolicy.RETURN_NULL_AND_BLANK).ToString(); 


Hi,

I downloaded project: Read___write_XLSX_via_NPOI___display_in_GRID - 1.4 MB a moment ago
Then, I have used all .dll in project to apply for my software. However, I meet this problem as follow:

Function with name "StringCellValue" didn't return value.
For instance:
In excel file: value[2, 3] = 4;
Run code:
sheet.getRow(2).GetCell(3).StringValueCell --> error

However, if value[2, 3] = N/A
=> Run code: sheet.getRow(2).GetCell(3).StringValueCell --> "N/A"

Due to, I thought that this function don't return value in format interger/number...
Please help me answer this question!
Thanks in advanced!

This is an annoying feature of NPOI - you need to check the CellType to see which of the *CellValue properties you can use. If the CellType returns Formula, then you'll also need to check the CachedFormulaResultType property.

The StringCellValue property only works if the cell is blank, a string, or a formula which returns a string.

If you set the cell's value to 4, the type will be Numeric, which means you must use the NumericCellValue.

If you just want the formatted value as a string, regardless of the cell's type, you can use the ToString method on the cell.

You also need to look out for empty cells - by default, NPOI skips any empty cell in the GetCell method, so cell 2 might not be the second column. To avoid this, you need to pass MissingCellPolicy.RETURN_NULL_AND_BLANK to the GetCell method.

string value = sheet.GetRow(2).GetCell(3, MissingCellPolicy.RETURN_NULL_AND_BLANK).ToString();