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

1 回答 1

37

经过一番搜索,我找到了解决方案。显然,在将 MemoryStream 作为附件传递之前,我需要明确设置它的起始位置。以下代码行成功了:

outputStream.Position = 0;
于 2012-10-11T20:51:18.587 回答