处理思路:
1.打开excel 用NPOI进行读取;
2.读取第一个Sheet;
读取过程中:
a.先设置相应列 不隐藏
b.读取Cell时 先判断是否的包含公式
相应代码如下:
public static DataTable ReadDataFromExcelByNPOI() { DataTable dt = new DataTable(); var filePathAndName = Path.Combine(Server.MapPath("~/Content/Excel"), "ExcelForUploadTest.xls"); //打开文件读取数据 stream = System.IO.File.Open(filePathAndName2, FileMode.Open); //通过Stream创建Workbook HSSFWorkbook workbook = new HSSFWorkbook(stream); //获取excel的第一个sheet HSSFSheet sheet = (HSSFSheet)workbook.GetSheetAt(0); //设置隐藏列 为 不隐藏 for (int iHide = 0; iHide <= 40; iHide++) { sheet.SetColumnHidden(iHide, false); } //最后一列的标号(即总的行数) int rowCount = sheet.LastRowNum; //获取sheet的首行 HSSFRow headerRow = (HSSFRow)sheet.GetRow(0); //一行最后一个方格的编号(即总的列数) int cellCount = headerRow.LastCellNum; string columnNames = @"A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z, AA,AB,AC,AD,AE,AF,AG,AH,AI,AJ,AK,AL,AM,AN,AO,AP,AQ,AR,AS,AT,AU,AV,AW,AX,AY,AZ"; string[] columns = columnNames.Split(‘,‘); //使用 A B C D ... 字母的方式 命名DataTable的各列名 for (int i = headerRow.FirstCellNum; i < cellCount; i++) { //DataColumn column = new DataColumn(headerRow.GetCell(i).StringCellValue); DataColumn column = new DataColumn(columns[i]); dt.Columns.Add(column); } for (int i = (iHeaderRowIndex.Value + 1); i <= rowCount; i++) { HSSFRow row = (HSSFRow)sheet.GetRow(i); DataRow dataRow = dt.NewRow(); if (row != null) { for (int j = row.FirstCellNum; j < cellCount; j++) { if (row.GetCell(j) != null) { //如果是公式Cell //则仅读取其Cell单元格的显示值 而不是读取公式 if (row.GetCell(j).CellType == CellType.FORMULA) { dataRow[j] = row.GetCell(j).StringCellValue; }else{ dataRow[j] = row.GetCell(j).ToString(); } } } } //某标示列 33 //某标示列 38 //其值非空 标示是有效数据 //其值为空 标示结束 if(string.IsNullOrEmpty(dataRow[33].ToString()) && string.IsNullOrEmpty(dataRow[38].ToString()) ) { break;//读取结束 退出For循环 } else { dt.Rows.Add(dataRow); } } workbook = null; sheet = null; return dt; } #endregion
时间: 2024-11-06 10:08:58