gpt4 book ai didi

asp.net-mvc - ASP.NET MVC 返回 Excel 文件

转载 作者:行者123 更新时间:2023-12-02 04:53:15 25 4
gpt4 key购买 nike

我需要上传文件并修改然后返回相同的文件。我不需要将文件保存到任何位置,而是操作它并返回。但是我不知道如何返回文件。

下面的代码允许保存文件,我什至编写了不保存文件的代码。唯一的问题是我收到一个错误,表明该文件已被其他用户打开。

该进程无法访问文件“D:\Places\places\App_Data\877d36d3-ce29-48d1-995a-ea6652a528a7C2.xlsx”,因为该文件正在被另一个进程使用。

你能帮我吗

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult FileUpload(HttpPostedFileBase uploadFile)
{
if (uploadFile.ContentLength > 0)
{
string path = string.Empty;
var fileName = Path.GetFileName(uploadFile.FileName);
path = Path.Combine(Server.MapPath("~/App_Data/"), Guid.NewGuid() + fileName);
uploadFile.SaveAs(path);

Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(path);
Excel._Worksheet xlWorksheet = (Excel._Worksheet)xlWorkbook.Sheets[1];
Excel.Range xlRange = xlWorksheet.UsedRange;
int rowCount = xlRange.Rows.Count; int colCount = xlRange.Columns.Count;
(xlRange.Cells[4, 5] as Excel.Range).Value2 = "asdF";
(xlRange.Cells[4, 6] as Excel.Range).Value2 = "asdF";
(xlRange.Cells[4, 7] as Excel.Range).Value2 = "asdF";
(xlRange.Cells[4, 8] as Excel.Range).Value2 = "asdF";

releaseObject(xlWorksheet);
releaseObject(xlWorkbook);
releaseObject(xlApp);
GC.Collect();

uploadFile.InputStream.Dispose();
return File(path, "application/text");

}
else
{
return View();
}
}

private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
//MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
}
finally
{enter code here
GC.Collect();
}
}

最佳答案

在操作中您可以返回 FileStreamResult

return new FileStreamResult([memory stream], "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

您可能还想在返回之前关闭工作簿并将其保存到临时区域。从错误来看,文件似乎仍然打开。

关于asp.net-mvc - ASP.NET MVC 返回 Excel 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15204089/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com