【问题标题】:How to create Excel file using OpenXML without creating a local file?如何使用 OpenXML 创建 Excel 文件而不创建本地文件?
【发布时间】:2015-04-27 04:59:05
【问题描述】:

是否可以在不创建本地文件的情况下使用 OpenXML SDK 创建和编辑 Excel 文档?

根据文档,Create 方法需要 filepath,它会创建文件的本地副本。

SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Create(filepath, SpreadsheetDocumentType.Workbook);

我在这里指的是 MSDN 文章: https://msdn.microsoft.com/en-us/library/office/ff478153.aspx

我的要求是创建文件,它应该由浏览器在单击按钮时下载。

有什么建议吗?

【问题讨论】:

    标签: c# excel openxml openxml-sdk


    【解决方案1】:

    您可以使用 SpreadsheetDocument.Create 的重载,它接受 Stream 并将其传递给 MemoryStream

    MemoryStream memoryStream = new MemoryStream();
    SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Create(memoryStream, SpreadsheetDocumentType.Workbook);
    
    //add the excel contents...
    
    //reset the position to the start of the stream
    memoryStream.Seek(0, SeekOrigin.Begin);
    
    return new FileStreamResult(memoryStream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
    

    请注意,根据this StackOverflow question,您不需要释放 Stream,因为它将由 FileStreamResult 类为您完成。

    【讨论】:

    • 这仍然会将数据缓冲到内存中。我发现这个选项可以使用只写不可搜索的流创建一个 excel 文件:codeproject.com/articles/347759/…
    • 我采用相同的方法,但下载了一个损坏的文件。你能帮我解决这个问题吗?可能是什么原因?
    • 说实话@Amrendra 可以是任意数量的事情。如果您提出新问题,我会尝试查看。
    【解决方案2】:

    添加另一个答案,因为我花了太多时间搜索这个:将 SpreadsheetDocument 保存到流的另一种方法是调用 SpreadsheetDocument.Clone(Stream s)

    即使您从文件或不想保存到的流中创建文档,它也能让您保存到流中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-03
      • 2019-07-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多