我尝试使用 NPOI 2.0 库将 .xlsx 文件转换为 DataTable 格式。没关系,但是我在转换为字符串日期单元格时遇到了问题。当我尝试使用 row.GetCell(j).ToString() 之类的构造时,它会抛出异常“无法从文本单元格中获取数值”。我尝试使用 DateCellValue 属性,但它也抛出了这个异常。使用其他单元格格式效果很好。功能,我使用它是:
private DataTable xlsxToDT(string fileName)
{
DataTable table = new DataTable();
XSSFWorkbook workbook = new XSSFWorkbook(new FileStream(fileName, FileMode.Open, FileAccess.Read));
ISheet sheet = workbook.GetSheetAt(0);
IRow headerRow = sheet.GetRow(0);
int cellCount = headerRow.LastCellNum;
for (int i = headerRow.FirstCellNum; i < cellCount; i++)
{
DataColumn column = new DataColumn(headerRow.GetCell(i).StringCellValue);
table.Columns.Add(column);
}
int rowCount = sheet.LastRowNum;
for (int i = (sheet.FirstRowNum); i < sheet.LastRowNum; i++)
{
IRow row = sheet.GetRow(i);
DataRow dataRow = table.NewRow();
for (int j = row.FirstCellNum; j < cellCount; j++)
{
if (row.GetCell(j) != null)
{
//EXCEPTION GENERATING IN THIS CODE
dataRow[j] = row.GetCell(j).ToString();
////////////////////////////
}
}
table.Rows.Add(dataRow);
}
workbook = null;
sheet = null;
return table;
}
更新:如果我插入代码
row.GetCell(j).SetCellType(CellType.STRING);
在问题单元格中,我的值类似于“36496.392581018517”。另一个单元格正确转换