问题描述
我不明白是什么问题,我正在从上传文件夹中读取 excel 文件,然后我想更新该文件并将其另存为新的 xlxs 文件
错误异常详细信息:System.Runtime.InteropServices.COMException:无法访问“System.IO.MemoryStream”。
Excel.Application xlApp = new
Microsoft.Office.Interop.Excel.Application();
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
path = System.IO.Path.Combine(Server.MapPath("~/Uploads/Contactless.xls"));
xlWorkBook = xlApp.Workbooks.Open(path);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
xlWorkSheet.Cells[2,1] = "will test sheet";
using (var stream = new MemoryStream())
{
xlWorkBook.SaveAs(stream);
var content = stream.ToArray();
return File(content,"application/vnd.openxmlformats-officedocument-spreadsheetml.sheet","contactless.xlsx");
}
解决方法
我认为您最终需要清理 InteropServices。
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Open(sFile);
xlWorkSheet = xlWorkBook.Worksheets["Sheet1"];
xlWorkSheet.Cells[2,1] = "will test sheet";
xlWorkBook.Close();
xlApp.Quit();
// CLEAN UP.
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWorkBook);
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWorkSheet);