我尝试使用 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”。另一个单元格正确转换
Excel 文件的第二列具有日期格式 (12/2/1999
)。在您当前的文化(“ru-RU”)中,NPOI 无法识别此格式。这似乎是 NPOI 中的一个错误,因为当发生这种情况时,无法从该单元格读取任何内容。我想到的唯一方法是在读取 excel 文件之前更改线程的区域性(并在之后将其更改回来):
private DataTable xlsxToDT(string fileName)
{
var prevCulture = Thread.CurrentThread.CurrentCulture;
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
try
{
// Put your whole method body here.
}
finally
{
Thread.CurrentThread.CurrentCulture = prevCulture;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)