从httppostedfilebase Excel文件读取单个单元格值

我有一个Excelfile,客户端发送到服务器作为httppostedfilebase,我需要知道如何从这个文件中读取值。

[HttpPost] public ActionResult ShowExcelFile(GetExcel model) { var file = model.Files[0]; FileInfo info = new FileInfo(file.FileName); var fileName = Path.GetFullPath(file.FileName); if (file != null && file.ContentLength > 0) { using (ExcelPackage package = new ExcelPackage(info)) { //Read some cell value, how? } } return View("ShowExcelFile"); } 

我的模特:

 public class GetExcel { public List<HttpPostedFileBase> Files { get; set; } public GetExcel() { Files = new List<HttpPostedFileBase>(); } } 

我的看法:

 @using (Html.BeginForm("ShowExcelFile", "ShowExcel", FormMethod.Post, new { enctype = "multipart/form-data" })) { @Html.TextBoxFor(m => m.Files, new { type = "file", name = "Files" })<br /> <input type="submit" value="Upload file" /> } 

我真的不现在怎么做,我已经尝试了Excel数据读取器,但它不能读取公式的值。 我只是不想从客户端发送的这个excelfile中读取单元格的值

据我所知,你使用EPPlus库。 为了得到你需要写的价值,就像那样

 public void Upload(HttpPostedFileBase file) { package.Load(file.InputStream); var worksheet = package.Workbook.Worksheets.First(); var cellValue = worksheet.Cells[rowIndex, columnIndex].Value; var formulaValue = worksheet.Cells[rowIndex, columnIndex].Formula; } 

让我们把你的控制器行动,你会得到的文件:

  [AcceptVerbs(HttpVerbs.Post)] public JsonResult ShowExcelFile() { // For getting the file that is Uploadeded. HttpPostedFileBase fileUpload = Request.Files["Files"]; byte[] data; using (Stream inputStream = fileUpload.InputStream) { MemoryStream memoryStream = inputStream as MemoryStream; if (memoryStream == null) { memoryStream = new MemoryStream(); inputStream.CopyTo(memoryStream); data = memoryStream.ToArray(); return Json(data, JsonRequestBehavior.AllowGet); } } return Json(new { }, JsonRequestBehavior.AllowGet); } 

控制器和视图如何实现有几个问题。 例如,您的ActionResult期望List<HttpPostedFileBase> ,但视图发布HttpPostedFileBase

但是 ,除此之外,在package内使用,请尝试:

 ExcelWorksheet worksheet = package.Workbook.Worksheets[1]; worksheet.Select(new ExcelAddress("A1")); //there is more than one way to set this string cellVal = (string)worksheet.SelectedRange.Value;