【问题标题】:OpenXML SpreadsheetDocument SaveAs() giving file-in-use errorOpenXML SpreadsheetDocument SaveAs() 给出文件使用错误
【发布时间】:2020-05-05 19:55:02
【问题描述】:

我正在尝试使用从 ASP.Net Core Web 应用程序调用的 OpenXMLPowerTools v4.5.3.2、DocumentFormat.OpenXML v2.9.1 动态生成 Excel 电子表格。

我已经验证可以生成电子表格了。

问题是我需要生成电子表格......并将其作为 MEMORY STREAM 返回(因此 ASP.Net Core Web 控制器

HCExcelReport.cs:

   class HCExcelReport
    {
        protected SpreadsheetDocument doc;
        protected MemorySpreadsheet ms;
        protected string tmpFile = System.IO.Path.GetTempFileName();

        public MemoryStream Generate(List<CandidateRecords> candidateRecords)
        {
            MemoryStream memoryStream = null;
            using (OpenXmlMemoryStreamDocument streamDoc = OpenXmlMemoryStreamDocument.CreateSpreadsheetDocument())
            {
                doc = streamDoc.GetSpreadsheetDocument();
                ms = new MemorySpreadsheet();

                ...
                // Save to disk=
                doc.SaveAs(tmpFile);  // <-- Successfully writes .. but file remains open
                doc.Dispose();   // <-- file *STILL* remains open
            }

            // Copy to memory stream
            using (FileStream fileStream = new FileStream(tmpFile, FileMode.Open, FileAccess.Read))  // <-- Exception: the file is in use by another process!!!!
            {
                memoryStream = new MemoryStream();
                fileStream.CopyTo(memoryStream);
                memoryStream.Position = 0;
            }
            return memoryStream;

我尝试了无数的东西......

...但是如果我使用 PowerTools,我看不到任何替代 doc.SaveAs()...

...如果我使用doc.SaveAs(),该文件似乎会一直“使用中”,直到我的网络应用退出。

问:有什么建议吗?

【问题讨论】:

标签: c# excel openxml openxml-powertools


【解决方案1】:

请看这个帖子How to copy a file while it is being used by another process

// Copy to memory stream
using (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
    memoryStream  = new MemoryStream();
    fs.CopyTo(memoryStream );
    fs.Close();
}
return memoryStream;

问候马塞尔

【讨论】:

  • 谢谢,但我最终放弃了 OpenXMLPowerTools。它不应该不必要地让文件“锁定”,我不应该采取“极端措施”(如使用您的链接中引用的卷影复制服务(VSS))。您的解决方案 (fs.CopyTo()) 没有那么激烈......但它仍然没有必要。不管怎样,谢谢你。让我“接受”你的回复:)
猜你喜欢
  • 1970-01-01
  • 2012-04-03
  • 2013-04-16
  • 1970-01-01
  • 1970-01-01
  • 2020-02-26
  • 1970-01-01
  • 2015-11-11
  • 1970-01-01
相关资源
最近更新 更多