OpenXML SpreadsheetDocument SaveAs() giving file-in-use error

天涯浪子 提交于 2020-07-23 02:26:12

问题


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.

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 ...

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

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

Q: Any suggestions?


回答1:


Please look at this post 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;

regards marcel



来源:https://stackoverflow.com/questions/61621885/openxml-spreadsheetdocument-saveas-giving-file-in-use-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!