Saving WorkBook to MemoryStream and Then Attaching to an Email

Hi,

I am able to create an xls report but when I choose to save it to memory stream and then attach it to an email it all works but I get a blank email that contains nothing, I am using .net framework 2.0. Any help would be appreciated.

Moe,

private static System.IO.MemoryStream CreateReportMethod()

{

MemoryStream ms = null;

MemoryStream excelStream = new MemoryStream_(Resources.ReportsResources.BackGroundRevisionHistoryReport) ;



Aspose.Cells.Workbook Excel = new Workbook();


Excel.Open(excelStream);

Worksheets Sheet = Excel.Worksheets;

Excel.CalculateFormula();
ms = new MemoryStream();

Excel.Save("C:\\abc.xls",Aspose.Cells.FileFormatType.Excel2003); //This works and produces the file in Excel2003 format, I am able to open the work book and view it.

Excel.Save(ms, FileFormatType.Excel2003);

excelStream.Dispose();

return ms ;

}

Calling Method

System.IO.MemoryStream memoryStream = null;

memoryStream = CreateReport() ;

sendMessage( all the parameters including the MemoryStream generated by CreateReport() ) ;

private static bool SendMessage(string fromAddress, string toAddress, string ccAddress, string subject, string body, bool isBodyHtml,MemoryStream ms,string attachmentName )
{

MailMessage mail = new MailMessage();
try
{
mail.To.Add(new MailAddress(toAddress));
mail.From = new MailAddress(fromAddress);
mail.Subject = subject;
mail.Body = body;
mail.IsBodyHtml = isBodyHtml;
//removed the following and harcoded the mediaType to be able to attach an excel email MHB
// if(mediaType == "Excel" )
// {
// mediaType = MediaTypeNames.Application.Octet ;
//}
if (ms != null)
{
mail.Attachments.Add(new Attachment(ms, attachmentName,"application/vnd.ms-excel")); }
if (!String.IsNullOrEmpty(ccAddress))
mail.CC.Add(ccAddress);

SmtpClient smtp = new SmtpClient();
smtp.Port = MedpackConstants.EMAIL_PORT;
smtp.Host = MedpackConstants.EMAIL_HOST;
smtp.Send(mail);

return true;
}
catch
{
return false;
}

finally
{
mail.Dispose();
}
}


Hi,

Thank you for considering Aspose.

Please add ms.Seek(0, SeekOrigin.Begin); before adding the stream as attachment. Please updated your code as below:

if (ms != null)
{

ms.Seek(0, SeekOrigin.Begin);

mail.Attachments.Add(new Attachment(ms, "new", "application/vnd.ms-excel"));

}

Thank You & Best Regards,

1 Like

Thanks for the quick response, that works I just needed to seek the begining of the MemoryStream. Thanks a lot.