NPOI with ASP.NET (C#)
本文关键字:NET with ASP NPOI | 更新日期: 2023-09-27 18:22:17
我正在尝试让NPOI与ASP.NET(C#)一起工作,我想读取一个excel文件并将其放入数据集中。这是我尝试的代码:
public static DataTable getExcelData(string FileName, string strSheetName)
{
DataTable dt = new DataTable();
HSSFWorkbook hssfworkbook;
using (FileStream file = new FileStream(FileName, FileMode.Open, FileAccess.Read))
{
hssfworkbook = new HSSFWorkbook(file);
}
ISheet sheet = hssfworkbook.GetSheet(strSheetName);
System.Collections.IEnumerator rows = sheet.GetRowEnumerator();
while (rows.MoveNext())
{
IRow row = (HSSFRow)rows.Current;
if (dt.Columns.Count == 0)
{
for (int j = 0; j < row.LastCellNum; j++)
{
dt.Columns.Add(row.GetCell(j).ToString());
}
continue;
}
DataRow dr = dt.NewRow();
for (int i = 0; i < row.LastCellNum; i++)
{
ICell cell = row.GetCell(i);
if (cell == null)
{
dr[i] = null;
}
else
{
dr[i] = cell.ToString();
}
}
dt.Rows.Add(dr);
}
return dt;
}
我得到的错误是
+ $exception {"Object reference not set to an instance of an object."} System.Exception {System.NullReferenceException}
奇怪的是,这实际上适用于我现有的两个excel文件,但当我放入第三个文件时,它会因错误而崩溃。
如果找不到strSheetName,则返回null
:
ISheet sheet = hssfworkbook.GetSheet(strSheetName);
尝试:
for( int iSheet = 0; iSheet < hssfworkbook.NumberOfSheets; ++iSheet )
{
ISheet sheet = hssfworkbook.GetSheetAt(iSheet); // could cast to HSSFSheet
String strSheetNameActual = sheet.SheetName;
}
然后找出要如何比较strSheetName
和strSheetNameActual
,或者要处理哪些图纸以及如何处理。
尝试使用这个:
for (int j = row.FirstCellNum; j < row.LastCellNum; j++)
和
for (int i = row.FirstCellNum; i < row.LastCellNum; i++)
代替:
for (int j = 0; j < row.LastCellNum; j++)
和
for (int i = 0; i < row.LastCellNum; i++)
此外,当第一行的单元格是null
:时,请确保您能够管理这种情况
if (dt.Columns.Count == 0)
{
int empty = 0;
for (int j = row.FirstCellNum; j < row.LastCellNum; j++)
{
ICell cell = row.GetCell(j);
if (cell == null)
{
dt.Columns.Add(String.Format("emptyColumnName_{0}", empty++));
}
else
{
dt.Columns.Add(row.GetCell(j).ToString());
}
}
continue;
}
如果你总是想从第一张表中读取(可能是为了去掉第二个方法参数,即表名,这也是你错误的原因),你可以使用:
// rest of the method's code
ISheet sheet = hssfworkbook.GetSheetAt(0);
if (sheet == null)
return dt;
var rows = sheet.GetRowEnumerator();
// rest of the method's code