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

Is it possible to create and edit an excel document using OpenXML SDK without creating a local file?
As per the documentation the Create method demands for a filepath, which creates a local copy of the file.
SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Create(filepath, SpreadsheetDocumentType.Workbook);
I'm referring the MSDN article here:
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?

You could use the overload of SpreadsheetDocument.Create that takes a Stream and pass it 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 question you don't need to dispose the Stream as it will be done for you by the FileStreamResult class.

Adding another answer as I spent way too much time searching for this: Another way to save a SpreadsheetDocument to a stream is by calling SpreadsheetDocument.Clone(Stream s)
It has the benefit of letting you save to a stream even if you created the document from a file or a stream you don't want to save to.

Related

Open workbook in Interop.Excel from byte array

I want to open Excel from byte[] because my file is encrypted and I want to open after decrypt but without write in a file.
The office has "restricted access" and I want to open my file with this protection but without saving the decrypted content in a file.
myApp.Workbooks.Open only supports a path.
Is it possible?
As an alternative to OpenXml there's also ExcelDataReader which from my experience is a lot faster in processing data compared to Interop.Excel(around 3 times+).
It can also open encrypted Excel files directly(stackoverflow)
The github page for ExcelDataReader has some great examples on how to use it. The only thing you'd have to do is:
This:
using (var stream = File.Open(filePath, FileMode.Open, FileAccess.Read))
Becomes this:
using (var stream = new MemoryStream(yourByte[])
And if you just want to open the password protected excel file you'd do this:
var conf = new ExcelReaderConfiguration { Password = "yourPassword" }; //Add this
excelReader = ExcelReaderFactory.CreateReader(stream, conf); //change the excel Reader to this
Make sure to check the Github page for more info!
It is not possible because the interop is actually an interface for programs to run and operate existing excel on the computer.
I think you need to use openxml created by Microsoft to work with excel word and PowerPoint.
DocumentFormat.OpenXml
Then you can use:
ExcelPackage excelPackage = new ExcelPackage(stream)
or
var pck = new OfficeOpenXml.ExcelPackage();
pck.Load(File.OpenRead(path));
pck.Load(Stream) can use any stream as input not only from a file.
It depends on your needs.

how to embed ole object directly. without saving any file in disk

I already created a docx file by aspose.word and I need to embed an worksheet to this file thus I created a workbook and worksheet .
Document doc = new Document();
Workbook workbook = new Workbook();
int i = workbook.Worksheets.Add();
Worksheet sheet = workbook.Worksheets[i];
and after filling cells in the sheet I save my excel file in storage and embedded it to my docx by using insertOleObject and pass file address to this method by using file stream.
workbook.Save(dir+"output.xlx");
Stream memStream = File.OpenRead(dir+"output.xlx");
Shape oleObject = builder.InsertOleObject(memStream, "Excel.Sheet.2",false,null);
but I want to embed a worksheet(or workbook) directly without using workbook.Save method and Stream object.
As bassfader shared, first save your Workbook to Memory Stream. Besides, you can convert your Memory Stream into Byte Array. Then you can use the same code as you have shown to insert Workbook (which is now in form of memory stream or byte array) as Ole Object in your MS-Word Document.
Note: I am working as Developer Evangelist at Aspose

open excel workbook from memorystream

I am trying to open an excel workbook from a memorystream. I have a web url of the excel file, what I do is I download the data from the url, then save it into a memorystream, but I am not sure how to open the workbook from the stream, here is how my code works so far.
WebClient wc = new WebClient();
byte[] fileArray = wc.DownloadData("url is inserted here");
MemoryStream ms = new MemoryStream(fileArray);
But from here I'm not sure how to go about reading the data from the stream to create the workbook, it doesn't seem like the spreadsheet document from http://msdn.microsoft.com/en-us/library/ff478410 works the way I want it to, any assistance or pointers would be appreciated
SpreadSheetDocument has an Open static method overload that takes stream as param for document source, just add to your code :
var doc = SpreadSheetDocument.Open(ms, isEditable);

OpenXML file download without temporary file

Is there a way of providing a download in an ASP.Net Page for a freshly generated OpenXML (docx) file without saving it in a temporary folder?
On MSDN I only found a tutorial for using a temp file but I thought about using the WordprocessingDocument.MainDocumentPart.GetStream() and directly writing the stream out.
When you create the document use a MemoryStream as the backing store. Then create and close the document normally and serve the contents of the memory stream to the client.
using(var stream = new MemoryStream())
{
using(var doc = WordprocessingDocument.Create(stream, WordprocessingDocumentType.Document, true)
{
...
}
stream.Position = 0;
stream.CopyTo(Response.OutputStream);
}
Do not just grab the MainDocumentPart because, as the name implies, this is just one part of the document package, not everything.
You'll also need to set response headers for content type and disposition.
Stream.CopyTo() in .NET 4.0 might help you out here.
WordprocessingDocument.MainDocumentPart.GetStream().CopyTo(Response.OutputStream);
You'll still need to set the headers for MIME type, content-disposition and so on.

iTextSharp - How to generate a RTF document in the ClipBoard instead of a file

I would like to generate a PDF or RTF document using iTextSharp library that can be copied to the clipboard, using the same code I use to generate the document on a file (FileStream).
This way my application would give the user two options: generate to a file or to the clipboard.
Basically every iTextSharp document is attached to a System.IO.Stream.
Document doc = new Document(PageSize.A4);
RtfWriter2.GetInstance(doc, stream);
Usually we save the document to a file, using FileStream. To use the same code to paste the document in the Clipboard, we use a MemoryStream instead.
MemoryStream stream = new MemoryStream();
Document doc = new Document(PageSize.A4);
RtfWriter2.GetInstance(doc, stream);
// (...) document content
doc.Close();
string rtfText = ASCIIEncoding.ASCII.GetString(stream.GetBuffer());
stream.Close();
Clipboard.SetText(rtfText, TextDataFormat.Rtf);
I only had problems with Images: It seems that iTextSharp exports images saving the bytes of the image after the \bin tag. Some libraries put the binary content encoded as hex characters. When I paste (from memory) in Word, the images won't appear, but if I load from a file, everything is OK. Any suggestions?

Categories