Question

I want to export an excel chart to Word as an object (Excel Chart), not as a picture. As picture is very easy with Chart.CopyPicture

I´m using AddOleObject, but it gives an error about not being able to link the file. This is the code:

Document doc; // Existing document
string chartSheet = xlsFilePath + "!" + chartSheetName;
string type = "Excel.Chart.8";
InlineShape shape = doc.Content.InlineShapes.AddOLEObject(ClassType: type, FileName: chartSheet, LinkToFile: false, DisplayAsIcon: false);

I´ve seen a lot of posts about importing excel to word, but nothing uptodate or that works.

For example:

This one is what I´m trying to do, although instead of a workbook of 1 sheet with a chart, I have a book with many charts so I insert the chart like file.xls!chartSheetname

This other uses copy and paste, only it inserts cells, not a chart. With chart, copy method copies the chart to antoher location in the workbook...

And with this one it adds an ole object to word, casts the object to a workbook, creates a worksheet and add data to that worksheet. But I already have the chart... I only want to insert an existing chart...

Was it helpful?

Solution

The problem was that I was using Office 2010, and when you open a .doc, it opens in Compatibilty Mode, and it seems you can´t insert a object from a .xlsx in a .doc in Compatibility Mode. So, I converted the .doc in .docx, open it as .docx and then insert it:

Word.Application wordAPP = new Word.Application();
Word.Document docx = wordAPP.Documents.Open(docFile, false, true, false, Format:Word.WdOpenFormat.wdOpenFormatXMLDocument);
Chart chart = xlsx.Charts[chartSheetName];
chart.ChartArea.Select();
chart.ChartArea.Copy();
docx.Application.Selection.PasteAndFormat(Word.WdRecoveryType.wdFormatOriginalFormatting);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top