我正在上传一个excel文件,并尝试阅读其内容。使用以下代码,它在localhost上正常工作。但是,如果我使用IIS上传到实时服务器,它将无法正常工作。奇怪的是,我上传的文件确实保存到服务器上的内容文件夹,但是在错误消息中它看起来是从我的本地计算机打开文件:
Microsoft.Office.Interop.Excel.Workbooks.Open(String Filename,Object UpdateLinks,Object ReadOnly,Object Format,Object Password,Object WriteResPassword,Object IgnoreReadOnlyRecommended,Object Origin,Object Delimiter,Object Editable,Object Notify,Object Converter,Object AddToMru ,Object Local,Object CorruptLoad)+0 Twilio4.Controllers.HomeController.Import(HttpPostedFileBase excelfile,SendMessageVal Model)
在C:\ Users \ sbudhai \ source \ repos \ SAP \ SAP \ Controllers \ HomeController.cs:111
[HttpPost]
public ActionResult Import(HttpPostedFileBase excelfile, SendMessageVal Model)
{
if(ModelState.IsValid == true)
{
if (excelfile == null || excelfile.ContentLength == 0)
{
ViewBag.Error2 = "Please select an excel file <br>";
return View(Model);
}
else
{
if (excelfile.FileName.EndsWith("xlsx") || excelfile.FileName.EndsWith("xls"))
{
string path = Server.MapPath("~/Content/" + excelfile.FileName);
if (System.IO.File.Exists(path))
System.IO.File.Delete(path);
excelfile.SaveAs(path);
//Read data from excel file
Excel.Application application = new Excel.Application();
Excel.Workbook workbook = application.Workbooks.Open(path);
Excel.Worksheet worksheet = workbook.ActiveSheet;
Excel.Range range = worksheet.UsedRange;
List<NUMBER> listProducts = new List<NUMBER>();
var C = range.Rows.Count;
var B = range.Rows.Count;
C++;
for (int row = 2; row < C; row++)
{
NUMBER p = new NUMBER();
p.NUMBER1 = long.Parse(((Excel.Range)range.Cells[row, 1]).Text);
listProducts.Add(p);
}
ViewBag.ListProducts = listProducts;
workbook.Close(path);
return View("Confirm", listProducts);
}
else
{
ViewBag.Error = "File type is incorrect <br>";
return View(Model);
}
}
}
else
{
return View(Model);
}
}
在服务器上使用Office Interop是not supported。
链接的文章描述了您将面临的一些问题。我建议使用替代品,如EPPlus,或商业产品,如Aspose Cells。
您可以使用OpenXML库而不是Office Interop,您将花时间尝试修复它,但最终会更好