【问题标题】:.net Save excel file [duplicate].net保存excel文件[重复]
【发布时间】:2021-10-03 22:45:40
【问题描述】:

我不明白是什么问题,我正在从上传文件夹中读取 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");

} 

【问题讨论】:

  • 不了解问题的原因是可以的,但您应该提供错误或错误行为的详细信息
  • xlWorkBook.SaveAs(stream);无法访问“System.IO.MemoryStream”。
  • 异常详细信息:System.Runtime.InteropServices.COMException:无法访问“System.IO.MemoryStream”。

标签: c# .net excel memorystream


【解决方案1】:

我认为您最终需要清理 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);

【讨论】:

    猜你喜欢
    • 2010-12-22
    • 1970-01-01
    • 2016-03-07
    • 1970-01-01
    • 1970-01-01
    • 2018-04-13
    • 2011-05-22
    • 2016-12-22
    • 1970-01-01
    相关资源
    最近更新 更多