我在更新Excel中的图表时遇到问题。
我使用c#代码插入行值,但现在插入数据后我想增加图表范围,以便它完全显示图表。我试过下面的代码。
请让我知道如何解决此问题。
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Open("E:\\test\\DT", 0, false, 5, "", "", false,
Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true, false, 0, true, 1, 0); //@"H:\TestFile.xlsx"
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Sheets.get_Item(1);
Workbook wb = xlApp.Workbooks.Add(XlSheetType.xlWorksheet);
Worksheet ws = (Worksheet)xlApp.ActiveSheet;
rng = ws.get_Range("A2", "A7");
// rng = ws.get_Range("Trend_NCM!$A$2:$AD$7",useDefault);
// rng = ws.get_Range() // //ActiveChart.SetSourceData
Source = rng("Trend_NCM!$A$2:$AD$7");
Excel.ChartObject chartObject11 = (Excel.ChartObject)ws.ChartObjects("Trend NCM");
chartObject11.Activate();
在第二张图片中,我手动拖动图表,我只想通过c#对每次添加的新列进行操作。
答案 0 :(得分:0)
这样的事情会起作用吗? (在下面输入您需要的值,还要记得对com对象进行适当的清理)
Excel.Application app = new Excel.Application();
Excel.Workbook book;
Excel.Worksheet sheet;
Excel.ChartObject chartObj;
Excel.Chart chart;
Excel.Series series;
book = app.Workbooks.Open(@"Path to excel workbook");//Open the work book
sheet = book.Sheets["Sheet name"];//Select the sheet the chart is on
chartObj = sheet.ChartObjects("chart name");//Select the ChartObject
chart = chartObj.Chart; //Select the Chart from the ChartObject
series = chart.SeriesCollection(1);//Select the series you are changing
series.Values = (Excel.Range)sheet.Range["A1:A5"]; //or sheet.Range[sheet.Cells[1, 1], sheet.Cells[4, 5]] works too
修改强> 请尝试以下操作来更新整个数据源而不是单个系列。
Excel.Application app = new Excel.Application();
Excel.Workbook book;
Excel.Worksheet sheet;
Excel.ChartObject chartObj;
Excel.Chart chart;
book = app.Workbooks.Open(@"Path to workbook");//Open the work book
sheet = book.Sheets["sheet name"];//Select the sheet the chart is on
chartObj = sheet.ChartObjects("Chart name");//Select the ChartObject
chart = chartObj.Chart; //Select the Chart from the ChartObject
chart.SetSourceData(sheet.Range["A1:A5"], Excel.XlRowCol.xlColumns); //I do not know whether your charts creates series by column or row, but I assumed column