'how to change a cell value in a chart that is embedded in a word document using C#
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
Solution 1:[1]
Try using ws.Range["E4"].FormulaR1C1 = 90;
Solution 2:[2]
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
Solution 3:[3]
It is better use Aspose.word that be cracked dll
in this section (Shape shape = (Shape)document.GetChild(NodeType.Shape, 0, true);) you can use for loop to find all shapes in your word doc and add i instead of 0
Document document = new Document(MyDir + "input.docx");
Shape shape = (Shape)document.GetChild(NodeType.Shape, 0, true);
if (shape.HasChart)
{
Chart chart = shape.Chart;
chart.Series.Clear();
String[] types = new String[] { "text1", "text2", "text3" };
double[] values = new double[] { 10d, 7d, 5d };
ChartSeries ser0 = chart.Series.Add("test", types, values);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | TechyGypo |
| Solution 2 | Juvilnoz |
| Solution 3 |
