如何使用OpenXML创建Excel文件而无需创建本地文件?

23

使用OpenXML SDK是否可以创建和编辑Excel文档而无需创建本地文件?

根据文档,Create方法需要一个filepath参数,这将创建文件的本地副本。

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

我这里参考了MSDN的文章:https://msdn.microsoft.com/en-us/library/office/ff478153.aspx

我的要求是创建一个文件,并且当用户单击按钮时,应该由浏览器下载。

有什么建议吗?

2个回答

45

您可以使用重载的 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");

请注意,根据这个 StackOverflow 问题,您不需要处理流的释放,因为FileStreamResult类会为您完成此操作。


这仍会将数据缓冲到内存中。我发现使用只写非可寻址流创建Excel文件的选项:https://www.codeproject.com/articles/347759/generate-excel-file-on-the-fly-without-using-micro - Sal
1
我正在遵循相同的方法,但下载了一个损坏的文件。你能帮我解决一下吗?可能是什么原因呢? - Amrendra
说实话,这可能是许多事情中的任何一件事,@Amrendra。如果您开一个新问题,我会尝试去看一下。 - petelids
memoryStream.Seek(0, SeekOrigin.Begin); 帮助我解决了文件损坏的问题。如果没有这行代码,文件将无法正常读取。 - Matt Fricker

2

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

它的好处是让你即使从文件或不想保存到的流创建文档,也可以保存到流中。


是的,在具有“模板”文件的情况下,克隆方法非常有用。 - M. Jahedbozorgan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接