DataTable dt = new DataTable();
using (FileStream file = new FileStream(@"C:UsersAdministratorDesktop导入datatable导入datatableOK.xlsx", FileMode.Open, FileAccess.Read))
{
XSSFWorkbook hssfworkbook = new XSSFWorkbook(file);
NPOI.SS.UserModel.ISheet sheet = hssfworkbook.GetSheetAt(0);
var row1 = sheet.GetRow(0);//获取第一行即标头
int cellCount = row1.LastCellNum;//第一行的列数
//把第一行的数据添加到datatable的列名
for (int i = row1.FirstCellNum; i < cellCount; i++)
{
DataColumn column = new DataColumn(row1.GetCell(i).StringCellValue);
dt.Columns.Add(column);
}
int row = sheet.LastRowNum;
for (int i = sheet.FirstRowNum+1; i <= sheet.LastRowNum; i++)
{
IRow row2 = sheet.GetRow(i);
DataRow datarow = dt.NewRow();
for (int j = row2.FirstCellNum; j < cellCount; j++)
{
if (row2.GetCell(j)!=null)
{
datarow[j] = row2.GetCell(j);
}
}
dt.Rows.Add(datarow);
}
}