使用NPOI读取Excel里的数据

DataTable dt = new DataTable();
using (FileStream file = new FileStream(@"C:\Users\Administrator\Desktop\导入datatable\导入datatable\OK.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);
}
}

posted @ 2016-07-01 22:48  Jesh_95  阅读(793)  评论(0编辑  收藏  举报