2011-08-18 145 views
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 
         ); 
       } 
      } 
     } 

回答

3

在您的WorkbookPart內部,您需要添加一個指定工作簿中每張工作表的元素。這是棘手寫上去正是你需要你的代碼,因爲你已經得到了很多未分配的創作者的變化,但基本上你需要:

workbook1.AddNamespaceDeclaration("r","http://schemas.openxmlformats.org/officeDocument/2006/relationships"); 
Sheets sheets1 = new Sheets(); 
Sheet sheet1 = new Sheet(){ Name = "Sheet1", SheetId = (UInt32Value)1U, Id = "R71b609d3bfb541ee" }; 
sheets1.Append(sheet1); 
workbook1.Append(sheets1); 
workbookPart1.Workbook = workbook1; 

你必須得到RELID標識,並把在那裏,但你應該很好走。

希望有幫助!

+2

如果有人感興趣,我只寫了一篇關於使用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 –

+0

謝謝克里斯,那是有用的 – gimpy

相關問題