MVC Excel Email Attachment with NPOI

    The First Question I had after successfully creating a Excel sheet was how do I create an attachment from a stream? A second to be more specific was how do I add an attachment to an email using System.Net.Mail? Ultimately I wanted to have the Excel Exports in C# using NPOI but I started small and thankfully others had already asked and answered these questions. After which was just a matter of knowing What the correct content-type for excel files was?

First Attempt
MailMessage mail = new MailMessage();
HSSFWorkbook workbook = CreateExcel(OrderId);
MemoryStream ms = new MemoryStream(workbook.GetBytes());
mail.Attachments.Add(new Attachment(ms, "example.xls",
                     "application/vnd.ms-excel"));
_emailService.SendEmail("example@example.com", 
                 "Email test", "Testing 123");
Changed it to..
MemoryStream ms = new MemoryStream();
workbook.Write(ms);
This was based on the QA "NPOI - Sending workbook as email attachment."

Resources
HSSFWorkbook (POI API Documentation)
MemoryStream.Position Property (System.IO)

Popular posts from this blog

UI-Bootstrap Collapsible Sticky Footer

Installing Windows on Acer chromebook 15 cb3-532

Aspetcore: NLog with Postgresql