場景:今天做一個導入功能,通用的npoi 導入代碼,都是 先準備好一個datatable ,繪製標題列,然後遍歷excel ,循環賦值 .
正常情況下,如果表格內都有值,或者是 空字符串單元格也可以,即 所有單元格都是激活狀態.讀取正常
常用代碼這樣:
int rowCount = sheet.LastRowNum;
for (int i = startRow; i <= rowCount; ++i)
{
IRow row = sheet.GetRow(i);
if (row == null || row.Cells.Count == 0) continue; //沒有數據的行默認是null
DataRow dataRow = data.NewRow();
for (int j = row.FirstCellNum; j < cellCount; ++j)
{
if (row.GetCell(j) != null) //同理,沒有數據的單元格都默認是null
dataRow[j] = row.Cells[j];
// Convert.ToDateTime();
}
data.Rows.Add(dataRow);
}
}
但是如果中間有未激活的代碼 if (row.GetCell(j) != null) 這句就出錯了,因爲假如24列,但是中間有2個未激活單元格,那sheet.GetRow(i);
只有 22列,所以代碼運行到這就出錯,而且會導致table不對應賦值.
解決方法如下:
//最後一列的標號
int rowCount = sheet.LastRowNum;
for (int i = startRow; i <= rowCount; ++i)
{
IRow row = sheet.GetRow(i);
if (row == null || row.Cells.Count == 0) continue; //沒有數據的行默認是null
DataRow dataRow = data.NewRow();
for (int j = row.FirstCellNum; j < cellCount; ++j)
{
try
{
//防止中間有未激活的單元格 用row.GetCell(j) != null 判定空最後一個無效,不知道什麼原因,所以用try
int ColumnIndex = row.Cells[j].ColumnIndex; //獲取真正的列索引,防止列混亂,否則對應datatable列錯誤
dataRow[ColumnIndex] = row.Cells[j];
//if (row.GetCell(j) != null) //同理,沒有數據的單元格都默認是null
// dataRow[j] = row.Cells[j];
}
catch
{ }
// Convert.ToDateTime();
}
data.Rows.Add(dataRow);
}