ASP.NET MVC NPOI Excelへ

2006 ワード

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; //   
          }
      }
  }
}