how to change a cell value in a chart that is embedded in a word document using C#

1

I have a word document containing some text and two charts pasted from excel. I am using it as a template. I want to open the word document in C#, update chart data values and print the document. I can do all except being able to access the chart data. I am using Microsoft.Office.Interop.Word and Microsoft.Office.Interop.Excel (both V14). Here is my code:

Word.Application wordApp = new Word.Application();
Word.Document wordDoc = wordApp.Documents.Open("K.docx");

Word.InlineShape shape = wordDoc.InlineShapes[1];
Word.Chart chart = shape.Chart;

Excel.Workbook wb = chart.ChartData.Workbook;
Excel.Worksheet ws = wb.Worksheets[0];
ws.Cells["E4"] = 90;

wordDoc.PrintOut();
wordDoc.Close();
wordApp.Quit();

The fifth command produces this error:

Unspecified error (Exception from HRESULT:0x80004005 (E_FAIL)) System.Collections.ListDictionaryInternal

UPDATE: I solved the error in fifth command as follows:

Word.Application wordApp = new Word.Application();
Word.Document wordDoc = wordApp.Documents.Open("K.docx");

wordApp.ActiveDocument.InlineShapes[1].Chart.ChartData.Activate();
Word.InlineShape shape = wordDoc.InlineShapes[1];
Word.Chart chart = shape.Chart;

Excel.Workbook wb = chart.ChartData.Workbook;
Excel.Worksheet ws = wb.Worksheets["Sheet1"];
ws.Cells["E4"] = 90;

wordDoc.PrintOut();
wordDoc.Close();
wordApp.Quit();

This time ws.Cells["E4"] = 90; produces the following error:

The parameter is incorrect. (Exception from HRESULT:0x80070057 (E_INVALIDARG)) System.Collections.ListDictionaryInternal

c#
excel
charts
ms-word
asked on Stack Overflow Feb 6, 2014 by Sys Soft • edited Mar 3, 2015 by Deduplicator

2 Answers

0

Try using ws.Range["E4"].FormulaR1C1 = 90;

answered on Stack Overflow Aug 7, 2014 by TechyGypo
0

You can also do :

ws1.Cells[4, "E"].Value = 1000;

My problem which could happen also to people who need this feature : Interop Word & Excel : Can't close an Excel workbook embedded in Word document

answered on Stack Overflow Mar 21, 2020 by Juvilnoz

User contributions licensed under CC BY-SA 3.0