I want to attach a WorkBook to an email as a stream.
My code this, but when I open the attached Excel file from the email, it says the file is corrupted and cannot be opened.
When I use `SaveToFile` instead of `SaveToStream`, the file opens fine.
How can I resolve this issue when using `SaveToStream`?
- Code: Select all
Workbook workbook = new Workbook();
workbook.Version = ExcelVersion.Version2013;
Worksheet worksheet = workbook.Worksheets[0];
worksheet.InsertDataTable(tempDt, true, 1,1);
worksheet.AllocatedRange.AutoFitColumns();
MailMessage mail = new MailMessage();
SmtpClient smtpServer = new SmtpClient(myserver);
smtpServer.Port = 25;
mail.From = new MailAddress("norply@ex.com");
mail.To.Add(email);
using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) {
Attachment att;
workbook.SaveToStream(ms, FileFormat.Version2013);
ms.Flush();
att = new Attachment(ms, $"{DateTime.Now.ToString("yyyyMMdd")}.xlsx");
mail.Attachments.Add(att);
smtpServer.Send(mail);
}