ASP.NET MVC NPOI 汇入Excel

1.前台页面

@using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
         
         
}

2.Controller

[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
    if (Request.Files["file"].ContentLength > 0)
    {
        string extension = System.IO.Path.GetExtension(file.FileName);

        if (extension == ".xls" || extension == ".xlsx")
        {
            string fileLocation = Server.MapPath("~/Content/") + Request.Files["file"].FileName;
            if (System.IO.File.Exists(fileLocation)) // 驗證檔案是否存在
            {
                System.IO.File.Delete(fileLocation);
            }

            Request.Files["file"].SaveAs(fileLocation); // 存放檔案到伺服器上
        }
    }

    return this.RedirectToAction("Index");
}

3.Business层,前提是引用NPOI.dll

// 建立一個工作簿 Office 2003
HSSFWorkbook excel;

using (FileStream files = new FileStream(fileLocation, FileMode.Open, FileAccess.Read))
{
    excel = new HSSFWorkbook(files);

   // Excel 的哪一個活頁簿,有兩種方式可以取得活頁簿
  ISheet sheet = excel.GetSheetAt(0);  // 在第幾個活頁簿,饅頭建議使用,畢竟我們不知道使用者會把活頁部取神麼名字,先抓地一個在說!(從0開始計算)
  ISheet sheetb = excel.GetSheet("Name"); // 利用名稱擷取

  for (int row = 1; row <= sheet.LastRowNum; row++) // 使用For 走訪所有的資料列
 {
      if (sheet.GetRow(row) != null) // 驗證是不是空白列
      {
          for (int c = 0; c <= sheet.GetRow(row).LastCellNum; c++) // 使用For 走訪資料欄
          {
              // 資料取得,等等說明
              sheet.GetRow(row).GetCell(c).NumericCellValue; // 數值
              sheet.GetRow(row).GetCell(c).StringCellValue; // 字串
              sheet.GetRow(row).GetCell(c).BooleanCellValue; // 布林
              sheet.GetRow(row).GetCell(c).DateCellValue; // 日期
          }
      }
  }
}

你可能感兴趣的:(ASP.NET MVC NPOI 汇入Excel)