问题
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