我有一个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数据阅读器,但它无法读取公式值。我只是想从客户端
中读取这个exlfile发送的单元格值答案 0 :(得分:1)
据我了解,您使用的是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;
}
答案 1 :(得分:1)
让我们把它放在你的控制器动作中你将获得文件:
[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);
}
答案 2 :(得分:0)
有一些关于控制器和视图如何实现的问题。例如,您的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;