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

Ng-repeat: Order a List Vertically rather Horizontal

HTML5 Audio doesn't Autoplay for Chrome on Android

Updating Razor 2.0 to 3.0 with Asp.net MVC