tags:

views:

4805

answers:

6

How do I write an Excel workbook to a MemoryStream without first saving it to the file system?

All options within the Microsoft.Office.Interop.Excel.WorkBook save options take a filename.

+1  A: 

I have done extensive work with the PIA and with storing Excel files in a document repository and streaming it out to the browser, and I have not been able to find a solution to using the PIA without first writing the contents to the file system first.

I think that you are going to have to swallow the bullet and deal with the file system as an intermediary. The good news is that you can just give the file a unique name like a guid or use some other tempfilename method (not sure if one exists in .net) and just delete the contents when you are done.

Charles Graham
+1  A: 

If you only need basic functionality from Excel, you might want to create the Workbook as an Html stream. There is another question on SO that handless this.

This also solves some problems (you might not have yet) concerning the scalability of your solution.

GvS
+1  A: 

Another option would be to use this free library for exporting the workbook. The save method on the workbook class can either take a file name or a stream.

KevB
yeah this is the same as what I was saying but in a pre=built library. so long as you are fine with OpenXML format, this library looks like the way to go. (assuming you are happy with its quality and performance).
Anonymous Type
+1  A: 

You could try GemBox.Spreadsheet .NET Component for reading and writing Excel files of various formats like XLS, XLSX, ODS, CSV, HTML.

It supports saving spreadsheet data to stream.

+1  A: 

The only way you could do this is if you were prepared to create a custom object that allowed you to store all the various bits and pieces of data/formulas/vba/links/ole objects that you wanted to keep, copy from your workbook to the object, and then persist that object to a memory stream. In affect using your proxy object as a go between.

There is no way (as others have said) of writing an Excel file straight to memory.

With Excel 2007 OpenXML format, you could use the BeforeSave event of the workbook to have a custom method that first sets the Cancel parameter of the BeforeSave event to True, and then instead serialises the resultant xml package (that represents the file) into an object in memory.

Anonymous Type
+1  A: 

This can be done with Open XML SDK 2.0. Eric White has a great article on how to work with OOXML files in stream at Working with In-Memory Open XML Documents

Otaku