NPOI读取excel文件

获取excel里面的数据 放进datatable

 

if (this.fuUpload.HasFile)
{

//根据路径通过已存在的excel来创建HSSFWorkbook,即整个excel文档
HSSFWorkbook workbook = new HSSFWorkbook(this.fuUpload.FileContent);

//获取excel的第一个sheet
HSSFSheet sheet = workbook.GetSheetAt(0);

DataTable table = new DataTable();
//获取sheet的首行
HSSFRow 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 + 1); i < sheet.LastRowNum; i++)
{
HSSFRow row = sheet.GetRow(i);
DataRow dataRow = table.NewRow();

for (int j = row.FirstCellNum; j < cellCount; j++)
{
if (row.GetCell(j) != null)
dataRow[j] = row.GetCell(j).ToString();
}

table.Rows.Add(dataRow);
}

workbook = null;
sheet = null;

this.gvExcel.DataSource = table;
this.gvExcel.DataBind();
}

你可能感兴趣的:(Excel,文件,读取,NPOI)