【发布时间】:2019-11-19 14:29:04
【问题描述】:
我开发了一个在 IIS 服务器上运行的 ASP.Net MVC 应用程序。我编写了一个读取 CSV 并将其行插入数据库的代码。
[HttpPost]
public ActionResult InsertPosition(int id, HttpPostedFileBase position)
{
var posicoesExistentes = db.tbPositions.Where(s => s.id_unique == id).AsEnumerable();
foreach (tbPosition posicao in posicoesExistentes)
{
db.tbPositions.Remove(posicao);
}
if (!Directory.Exists(Server.MapPath("~/App_Data/")))
{
System.IO.Directory.CreateDirectory(Server.MapPath("~/App_Data/"));
}
string excelPath = Server.MapPath("~/App_Data/" + position.FileName);
if (System.IO.File.Exists(excelPath))
{
System.IO.File.Delete(excelPath);
}
position.SaveAs(excelPath);
string tempPath = Server.MapPath("~/App_Data/" + "tmp_" + position.FileName);
System.IO.File.Copy(excelPath, tempPath, true);
Excel.Application application = new Excel.Application();
Excel.Workbook workbook = application.Workbooks.Open(tempPath, ReadOnly: true,Editable:false);
Excel.Worksheet worksheet = workbook.ActiveSheet;
Excel.Range range = worksheet.UsedRange;
application.Visible = true;
for (int row = 1; row < range.Rows.Count - 1; row++)
{
tbPosition p = new tbPosition();
p.position = (((Excel.Range)range.Cells[row, 1]).Text == "") ? null : Convert.ToInt32(((Excel.Range)range.Cells[row, 1]).Text);
p.left = ((Excel.Range)range.Cells[row, 2]).Text;
p.right = ((Excel.Range)range.Cells[row, 3]).Text;
p.paper = ((Excel.Range)range.Cells[row, 4]).Text;
p.denomination = ((Excel.Range)range.Cells[row, 5]).Text;
p.material = ((Excel.Range)range.Cells[row, 6]).Text;
p.norme = ((Excel.Range)range.Cells[row, 7]).Text;
p.finalized_measures = ((Excel.Range)range.Cells[row, 8]).Text;
p.observation = ((Excel.Range)range.Cells[row, 9]).Text;
p.id_unique = id;
db.tbPositions.Add(p);
db.SaveChanges();
}
workbook.Close(true, Type.Missing, Type.Missing);
application.Quit();
System.IO.File.Delete(tempPath);
return Json("Success", JsonRequestBehavior.AllowGet);
}
但作为回报,我收到错误“Microsoft Excel 无法访问文件'...'。当我尝试打开请求的 Excel 文件时,有几个可能的原因。
我已经尝试以只读方式打开文件,我已经尝试授予指定文件夹的权限,关闭excel文件的多种方式,并创建原始文件的副本并读取他。但是在这些解决方案中的每一个中都不成功。我在这里错过了什么?
【问题讨论】:
-
如果是 csv,为什么不使用简单的“File.ReadAllLines()”?
-
也许这回答了你的问题stackoverflow.com/a/7386967/2972052
-
确保您为站点和 excel 文件夹分配了 iis_iusrs 和 iusr 权限,并且您在 iis 中启用了匿名身份验证。分配权限后,还需要在iis中刷新站点。此外,请检查您的应用程序池在哪个身份下运行。
标签: c# asp.net excel asp.net-mvc-4 iis