Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# OpenXML Embed Spreadsheet Chart in Word Document

I have generated a spreadsheet with data and a chart based on the data using C# OpenXML.

enter image description here

I am now wanting to now embed this chart into a word document, so that when these reports are sent out, the charts can be edited if need be (Not an external link).

I have looked around for hours and can't find any consistent documentation for articles which achieve this. Most leads seem to talk about 'EmbeddedPackageParts'.

If anyone has any helpful articles or can provide some clarity it would be appreciated.

Cheers, Duncan.

like image 233
Duncan Palmer Avatar asked Oct 16 '18 01:10

Duncan Palmer


1 Answers

I ended up figuring this out!

Steps:

  1. Generate xlsx file with my data in it.

  2. Save the xlsx file locally

  3. In my word document create a new chart part and generate the graph contents

    ChartPart wordChartPart = document.MainDocumentPart.AddNewPart<ChartPart>();
    string wordChartId = document.MainDocumentPart.GetIdOfPart(wordChartPart);
    WordDocumentBuilder.Workflows.SpreadsheetUtils.GenerateBarChartPart(wordChartPart, categories, dataRows);
    
  4. Embed the spreadsheet in the ChartPart

    EmbeddedPackagePart embeddedObjectPart = wordChartPart.AddEmbeddedPackagePart(@"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
    
    using (FileStream stream = new FileStream(file, FileMode.Open))
    {
        byte[] documentBytes = new byte[stream.Length];
    
        stream.Read(documentBytes, 0, documentBytes.Length);
    
        using (BinaryWriter writer = new BinaryWriter(embeddedObjectPart.GetStream()))
        {
            writer.Write(documentBytes);
            writer.Flush();
        }
    }
    
  5. I could then insert an Inline Drawing into my word document which referenced the chart part.

like image 134
Duncan Palmer Avatar answered Oct 12 '22 23:10

Duncan Palmer