我正在使用xlsx
库和C#
读取一个C#
文件。我需要提取一些excel列,并将提取的值保存到某种数据结构中。
我可以成功地读取该文件,并使用以下代码从第二行(第一个仅包含标题)到最后一行获取所有值:
...
workbook = new XSSFWorkbook(fs);
sheet = (XSSFSheet)workbook.GetSheetAt(0);
....
int rowIndex = 1; //--- SKIP FIRST ROW (index == 0) AS IT CONTAINS TEXT HEADERS
while (sheet.GetRow(rowIndex) != null) {
for (int i = 0; i < this.columns.Count; i++){
int colIndex = this.columns[i].colIndex;
ICell cell = sheet.GetRow(rowIndex).GetCell(colIndex);
cell.SetCellType(CellType.String);
String cellValue = cell.StringCellValue;
this.columns[i].values.Add(cellValue); //--- Here I'm adding the value to a custom data structure
}
rowIndex++;
}
我现在要做的是检查excel文件是空的还是只有1行,以便正确处理问题并显示消息
如果我对一个只有1行(标题)的excel文件运行我的代码,它就会中断。
cell.SetCellType(CellType.String); //--- here cell is null
有以下错误:
Object reference not set to an instance of an object.
我还试着用
sheet.LastRowNum
但是它没有返回正确的行数。例如,我创建了一个5行的excel (1xHEADER + 4xDATA),代码成功地读取了excel值。在同一excel上,我删除了4行数据,然后再次启动excel文件上的代码。sheet.LastRowNum
继续以结果形式返回4
,而不是1
.我认为这与一些与手工清理的工作表单元格有关的属性有关。
你对解决这个问题有什么建议吗?
发布于 2015-08-13 06:42:03
我认为使用sheet.LastRowNum是明智的,它应该返回当前工作表上的行数。
发布于 2016-05-26 15:59:32
我是不是太简单化了?
bool hasContent = false;
while (sheet.GetRow(rowIndex) != null)
{
var row = rows.Current as XSSFRow;
//all cells are empty, so is a 'blank row'
if (row.Cells.All(d => d.CellType == CellType.Blank)) continue;
hasContent = true;
}
发布于 2016-11-29 06:16:01
可以使用以下代码检索行数:
public int GetTotalRowCount(bool warrant = false)
{
IRow headerRow = activeSheet.GetRow(0);
if (headerRow != null)
{
int rowCount = activeSheet.LastRowNum + 1;
return rowCount;
}
return 0;
}
https://stackoverflow.com/questions/31344841
复制相似问题