- 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();
- }
- //该片段来自于http://www.codesnippet.cn/detail/290320132624.html
来源: http://www.codesnippet.cn/detail/290320132624.html