1
我試圖將行從另一電子表格保存到此方法,並將此電子表格保存爲電子郵件的附件。該電子郵件發送正常,但附件不打開的錯誤「文件已損壞,無法打開」。我試圖將文件保存到c:上的filstream,但得到了同樣的錯誤。這段代碼有什麼問題?文件損壞,使用openXML 2.0保存excel文檔時無法打開
public static void CreateErrorMailWithExcelAttachment(List<Row> rows)
{
if (rows.Count > 0)
{
using (MemoryStream stream = new MemoryStream())
{
//Create a spreadsheet document by supplying the file name.
using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Create(stream, SpreadsheetDocumentType.Workbook))
{
// Add a WorkbookPart to the document.
spreadsheetDocument.AddWorkbookPart();
spreadsheetDocument.WorkbookPart.Workbook = new Workbook();
spreadsheetDocument.WorkbookPart.AddNewPart<WorksheetPart>();
spreadsheetDocument.WorkbookPart.WorksheetParts.First().Worksheet = new Worksheet();
// create sheet data
spreadsheetDocument.WorkbookPart.WorksheetParts.First().Worksheet.AppendChild(new SheetData());
// Add Rows to the Sheet.
foreach (Row row in rows)
{
spreadsheetDocument.WorkbookPart.WorksheetParts.First().Worksheet.First().AppendChild(new Row(row.OuterXml));
}
spreadsheetDocument.WorkbookPart.Workbook.Save();
}
Dictionary<string, byte[]> attachments = new Dictionary<string, byte[]>();
attachments.Add("Book1.xlsx", stream.ToArray());
SendEmail
(
acsis.Common.AppContext.Configuration.GetValue(Constants.ApplicationName, "SMTPServer"),
acsis.Common.AppContext.Configuration.GetValue(Constants.ApplicationName, "SMTPUser"),
acsis.Common.AppContext.Configuration.GetValue(Constants.ApplicationName, "SMTPPass"),
"[email protected]",
acsis.Common.AppContext.Configuration.GetValue(Constants.ApplicationName, "InstitutionalDatabaseAdminEmail"),
"Failed rows from bulk investor spreadsheet upload",
"Test",
false,
attachments
);
}
}
}
如果有人感興趣,我只寫了一篇關於使用Open XML SDK創建最小尺寸XLSX文件的博客文章。 http://blogs.msdn.com/b/chrisrae/archive/2011/08/18/creating-a-simple-xlsx-from-scratch-using-the-open-xml-sdk.aspx –
謝謝克里斯,那是有用的 – gimpy