Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EPPlus with MemoryStream as email attachment -- file is empty

Tags:

.net

epplus

I'm building a console app that moves data into an excel file (using EPPlus library). I'm saving the ExcelPackage as a MemoryStream, and I want to attach it to an email. However, when I receive the email, the Excel file is empty -- 0 bytes.

Thoughts?

        MemoryStream outputStream = new MemoryStream();
        using (ExcelPackage package = new ExcelPackage(outputStream)) {

                // export each facility's rollup and detail to tabs in Excel (two tabs per facility)
                ExcelWorksheet facilityWorksheet = package.Workbook.Worksheets.Add(row["facility_id"].ToString());
                ExcelWorksheet facilityDetail = package.Workbook.Worksheets.Add(row["facility_id"].ToString() + "-detail");

                facilityWorksheet.Cells.LoadFromDataTable(rollupData, true);
                facilityDetail.Cells.LoadFromDataTable(rawExceptions, true);

                package.Save();
        }

Here's the code for creating the email attachment:

Attachment attachment = new Attachment(outputStream, "ECO_exceptions.xlsx", "application/vnd.ms-excel");
like image 354
Nate Avatar asked Oct 11 '12 19:10

Nate


1 Answers

After some more searching, I found the solution. Apparently I needed to explicitly set the starting position of the MemoryStream before I passed it in as an attachment. The following line of code did the trick:

outputStream.Position = 0;
like image 197
Nate Avatar answered Oct 20 '22 13:10

Nate