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:
- the email gets sent ok, complete with an attachment of the correct name
- however the attachment is empty
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)