Search code examples
c#openxmlopenxml-sdk

How to attach .eml file in Excel using OpenXML SDK?


I am using this code. It does attach the file but I can't see anything if I open the file using MS Excel application.

            string targetFile = "test returns tracker.xlsx";
            string placeholder = @"placeholder.PNG";
            string embed = @"embed.docx";
            using (SpreadsheetDocument document = SpreadsheetDocument.Open(targetFile, true))
            {
                WorkbookPart workbookpart = document.WorkbookPart;
                WorksheetPart sheet1 = workbookpart.WorksheetParts.First();   


                EmbeddedPackagePart newEmbeddedPackagePart = sheet1.AddNewPart<EmbeddedPackagePart>(@"application/vnd.openxmlformats-officedocument.wordprocessingml.document", "rId100");
                newEmbeddedPackagePart.FeedData(File.Open(embed, FileMode.Open));
                document.WorkbookPart.Workbook.Save();
                // Close the document handle.
                document.Close();
            }

Solution

  • newEmbeddedPackagePart.FeedData(File.Open(embed...
    

    Issue in your code is with FeedData. File.Open method gives you a stream but that's empty. You need to seek the data before you can expect that saved In excel as embedded doc

    Example of seek is

        FileStream SourceStream = File.Open(filename, FileMode.Open);
        SourceStream.Seek(0, SeekOrigin.End);
    

    Use this source stream in your FeedData to make it work.

    newEmbeddedPackagePart.FeedData(SourceStream);
    

    Now you can save the workbook and close the document

    References:

    1. http://www.ericwhite.com/blog/forums/topic/adding-workbook-to-chart-as-an-embeddedpackagepart/

    2. https://learn.microsoft.com/en-us/dotnet/api/system.io.filestream?view=netframework-4.8