C# 如何在不创建本地文件的情况下使用 OpenXML 创建 Excel 文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29887503/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 04:20:57  来源:igfitidea点击:

How to create Excel file using OpenXML without creating a local file?

c#excelopenxmlopenxml-sdk

提问by Bishnu D.

Is it possible to create and edit an excel document using OpenXML SDK without creating a local file?

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

As per the documentation the Createmethod demands for a filepath, which creates a local copy of the file.

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

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

I'm referring the MSDN article here: https://msdn.microsoft.com/en-us/library/office/ff478153.aspx

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

My requirement is to create the file, and it should be downloaded by the browser on clicking a button.

我的要求是创建文件,并且应该通过单击按钮由浏览器下载。

Any suggestion?

有什么建议吗?

采纳答案by petelids

You could use the overload of SpreadsheetDocument.Createthat takes a Streamand pass it a MemoryStream:

您可以使用 a 的重载SpreadsheetDocument.Create并将其Stream传递给 a 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");

Note that as per this StackOverflow questionyou don't need to dispose the Stream as it will be done for you by the FileStreamResultclass.

请注意,根据此 StackOverflow 问题,您不需要处置 Stream,因为它会由FileStreamResult班级为您完成。