OpenXML SpreadsheetDocument SaveAs()给出使用中的文件错误 [英] OpenXML SpreadsheetDocument SaveAs() giving file-in-use error

查看:75
本文介绍了OpenXML SpreadsheetDocument SaveAs()给出使用中的文件错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to generate an Excel spreadsheet dynamically, using OpenXMLPowerTools v4.5.3.2, DocumentFormat.OpenXML v2.9.1, called from a ASP.Net Core web app.

我已经确认能够生成电子表格.

I've verified that able to generate the spreadsheet OK.

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

The problem is that I need to generate the spreadsheet ... and return it as a MEMORY STREAM (so the ASP.Net Core web controller

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;

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

I've tried countless things ...

...但是,如果我使用PowerTools,则看不到 doc.SaveAs() ...

... But if I use PowerTools, I don't see any alternatives to doc.SaveAs()...

...而且,如果我使用 doc.SaveAs(),则该文件似乎一直保持使用中"状态,直到我的Web应用程序退出为止.

... And if I use doc.SaveAs(), the file seems to remain "in use" until my web app exits.

问:有什么建议吗?

推荐答案

请查看此帖子关注马塞尔

这篇关于OpenXML SpreadsheetDocument SaveAs()给出使用中的文件错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆