我有一個需要上傳文件和修改,然後返回相同的。我不需要將文件保存到任何位置,但操作它並返回。但是我不知道如何返回文件。ASP.NET MVC返回Excel文件
下面的代碼允許文件保存,我甚至用保存文件編寫代碼。唯一的問題是我收到一個錯誤,該文件已被其他用戶打開。
該進程無法訪問文件'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();
}
}
不確定它是否是正確的MIME類型的Excel工作簿。但這應該是一個快速的谷歌搜索找到。 – 2013-03-04 14:46:04