A client has asked me to enhance one of their apps in order to send out an email containing an excel spreadsheet. They happened to have an old copy of SpreadsheetGear (2009) lying around, so I thought it might save time if I used it.
As it happens SpreadsheetGear was great to actually create the spreadsheet, but I'm having trouble sending it as an email attachment. Just wondered if anyone had done this? In theory it should be pretty easy, my current code is as follows:
/// <summary>
/// Creates an email attachment based upon the inbound workbook
/// </summary>
/// <param name="workbook">The workbook</param>
/// <returns>an email Attachment</returns>
private static Attachment CreateAttachment(string id, IWorkbook workbook)
{
// Open up a memorystream and save out to it
System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();
workbook.SaveToStream(memoryStream, SpreadsheetGear.FileFormat.OpenXMLWorkbook);
return new Attachment(memoryStream, id + ".xls", "application/vnd.ms-excel");
}
where workbook is a fully-populated SpreadsheetGear workbook. After this, the Attachment object is pushed into a System.Net.Mail.MailMessage
object using
MailMessage.Attachments.Add(attachment);
What I am seeing is:
In a dev environment, I put some debug code in there along the lines
workbook.SaveAs("c:\\test.xls", SpreadsheetGear.FileFormat.OpenXMLWorkbook);
which yielded the desired spreadsheet, as a file. But obviously since I am ultimately just sending this electronically I'd just as soon avoid writing to the disk at all, if I can. Any pointers on where I've gone wrong?
Thanks, Pete
(should finally add that upgrading to the latest SpreadsheetGear is not an option, its either this approach or do it manually! And the environment is VS2008, .net 3.5)
I tried using the code in your question. It worked for me with two small modifications.
1) Since you are saving to the OpenXMLWorkbook format, I changed the extension to .xlsx instead of .xls.
2) I added the following line of code after saving the workbook.SaveToStream method.
memoryStream.Seek(0, System.IO.SeekOrigin.Begin);
This sets the position to the beginning of the stream. When I tried you code without it, I received an error when I tried to open the Excel attachment.
Without these modifications, I got errors, but I never got an empty attachment. I am using the most recent version of SSG, but I don't see why that should matter in this case.