using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using System.Data;
using System.IO;
using NPOI.XSSF.UserModel;
刚刚接触Excel导入导出,感觉用NPOI蛮方便的就研究了一下,下面是Excel导入读取到DataTable中的功能
#region
public DataTable ImportExcel(string filePath)
{
using (FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
try
{
hssfworkbook = new XSSFWorkbook(file);
}
catch (Exception ex)
{
hssfworkbook = new HSSFWorkbook(file);
}
}
ISheet sheet = hssfworkbook.GetSheetAt();
System.Collections.IEnumerator rows = sheet.GetRowEnumerator();
DataTable dt = new DataTable();
//获取列数,填充到DataTable中
for (int j = ; j < (sheet.GetRow().LastCellNum); j++)
{
dt.Columns.Add("列" + j);
}
//读取集合元素,递进读取
while (rows.MoveNext())
{
IRow row = (IRow)rows.Current;
DataRow dr = dt.NewRow();
for (int i = ; 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;
}
#endregion
在操作的时候有时候会出现“The supplied data appears to be in the Office 2007+ XML. POI only supports OLE2 Office documents ”错误,这是因为XSSFWorkbook支持.xlsx 2007格式,HSSFWorkbook 支持.xls 2003格式