` Here is my workbook I created. If I save this file on hard disc, all is working okey. But looks like XLWorkbook doesnt support .xls (I got an exception). But with xlsx all is okey.
var workbook = new XLWorkbook();
var worksheet = workbook.Worksheets.Add("TestWorksheet");
var currentRow = 1;
worksheet.Cell(currentRow, 1).Value = "Test Name";
worksheet.Cell(currentRow, 2).Value = "Test 1";
worksheet.Cell(currentRow, 3).Value = "Test 2";
worksheet.Cell(currentRow, 4).Value = "Test 3";
worksheet.Cell(currentRow, 5).Value = "Test 4";
//workbook.SaveAs(path "newFile.xlsx");
Then am trying to send it via email.
try
{
MemoryStream ms = new MemoryStream();
Console.WriteLine(ms.Length);
workbook.SaveAs(ms);
Console.WriteLine(ms.Length);
MailAddress from = new MailAddress(emailfFrom, "Me");
MailAddress to = new MailAddress(emailTo);
MailMessage m = new MailMessage(from, to);
m.Subject = "Test";
m.Body = "<h2>Some text here</h2>";
m.IsBodyHtml = true;
System.Net.Mail.Attachment attach = new System.Net.Mail.Attachment(ms, "file.xlsx", "application/excel");
m.Attachments.Add(attach);
SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
smtp.Credentials = new NetworkCredential(emailfFrom, password);
smtp.EnableSsl = true;
smtp.Send(m);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
When I check the email - I got the message and the file. But When I load the file that I got by email, and try to open it I have an error that the file type was wrong or file was destroyed. And it is empty inside and no worksheet that I created.
And also when I loaded this file it was without extention. I added extention .xlsl by hands but it didnt help.
Please help. This is something with memory stream or with Content type of attachment? I tried different ("application/excel", etc.).
Thank you.
CodePudding user response:
You need to reset the position of the memory stream after writing to it so that the stream is read from the beginning when sending the e-mail.
I.e. add this line just after workbook.SaveAs(ms);
and it will work as expected:
workbook.SaveAs(ms);
ms.Position = 0;