.NET小筆記-NPOI讀取excel內容到DataTable


下載比較新的NPOI組件支持excel2007以上的,把.dll添加引用

引入命名空間 

using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;

直接調用下面方法,把excel內容轉為DataTable

 /// <summary>
       /// 獲取excel內容
       /// </summary>
       /// <param name="filePath">excel文件路徑</param>
       /// <returns></returns>
       public static DataTable ImportExcel(string filePath)
       {
           DataTable dt = new DataTable();
           using (FileStream fsRead = System.IO.File.OpenRead(filePath))
           {
               IWorkbook wk = null;
               //獲取后綴名
               string extension = filePath.Substring(filePath.LastIndexOf(".")).ToString().ToLower();
              //判斷是否是excel文件
               if (extension == ".xlsx" || extension == ".xls")
               {
                   //判斷excel的版本
                   if (extension== ".xlsx")
                   {
                      wk = new XSSFWorkbook(fsRead);
                  }
                  else
                  {
                      wk = new HSSFWorkbook(fsRead);
                  }
              
               //獲取第一個sheet
              ISheet sheet = wk.GetSheetAt(0);
               //獲取第一行
              IRow headrow=sheet.GetRow(0);
              //創建列
              for (int i = headrow.FirstCellNum; i < headrow.Cells.Count; i++)
              {
                //  DataColumn datacolum = new DataColumn(headrow.GetCell(i).StringCellValue);
                  DataColumn datacolum = new DataColumn("F"+(i+1));
                  dt.Columns.Add(datacolum);
              }
              //讀取每行,從第二行起
              for (int r = 1; r <= sheet.LastRowNum; r++)
              {
                  bool result = false;
                  DataRow dr = dt.NewRow();
                  //獲取當前行
                  IRow row = sheet.GetRow(r);
                  //讀取每列
                  for (int j = 0; j < row.Cells.Count; j++)
                  {
                      ICell cell = row.GetCell(j); //一個單元格
                      dr[j] = GetCellValue(cell); //獲取單元格的值
                      //全為空則不取
                      if (dr[j].ToString() != "")
                      {
                          result = true;
                      }
                  }
                  if (result == true)
                  {
                      dt.Rows.Add(dr); //把每行追加到DataTable
                  }
              }
              }
              
          }
          return dt;
      }
//對單元格進行判斷取值
      private static string GetCellValue(ICell cell)
      {
          if (cell == null)
              return string.Empty;
          switch (cell.CellType)
          {
                 case CellType.Blank: //空數據類型 這里類型注意一下,不同版本NPOI大小寫可能不一樣,有的版本是Blank(首字母大寫)
                     return string.Empty;
                 case CellType.Boolean: //bool類型
                     return cell.BooleanCellValue.ToString();
                 case CellType.Error:
                     return cell.ErrorCellValue.ToString();
                 case CellType.Numeric: //數字類型
                     if(HSSFDateUtil.IsCellDateFormatted(cell))//日期類型
                     {
                         return cell.DateCellValue.ToString();
                     }
                     else //其它數字
                     {
                         return cell.NumericCellValue.ToString ();
                     }
                 case CellType.Unknown: //無法識別類型
                 default: //默認類型
                     return cell.ToString();//
                 case CellType.String: //string 類型
                     return cell.StringCellValue;
                 case CellType.Formula: //帶公式類型
                     try
                     {
                         HSSFFormulaEvaluator e = new HSSFFormulaEvaluator(cell.Sheet.Workbook);
                         e.EvaluateInCell(cell);
                         return cell.ToString();
                     }
                     catch
                     {
                         return cell.NumericCellValue.ToString();
                     }
             }
         }

測試例子

我把一個名為aaa.xlsx的excel放根目錄下,內容為

其中 C4是公式,其它的正常

執行代碼

string filePath = Server.MapPath("~/aaa.xlsx");
DataTable dt = new DataTable();
if (File.Exists(filePath))
{
dt = ImportExcel(filePath);
}

然后打斷點監測一下dt ,內容為

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM