EPPlus with MemoryStream as email attachment — file is empty

时光怂恿深爱的人放手 提交于 2021-02-06 08:00:23

问题


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");

回答1:


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;


来源:https://stackoverflow.com/questions/12847412/epplus-with-memorystream-as-email-attachment-file-is-empty

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!