简体   繁体   English

使用C#以编程方式增加Excel图表数据范围

[英]Excel Chart data range increase programatically using c#

I'm facing problem while updating a chart in excel. 在Excel中更新图表时遇到问题。

I'm inserting the row values using c# code, but now after inserting the data I want to increase the chart range so that it will fully show the graph . 我正在使用c#代码插入行值,但是现在在插入数据之后,我想增加图表范围,以使其完全显示图表。 i have tried the below code . 我试过下面的代码。

Please let me know how can I resolve this. 请让我知道我该如何解决。

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(); 

In the 2nd image , i'm dragging the chart manually , i just want to make it by c# only for the new columns which are added each time . 在第二张图片中,我手动拖动图表,我只想通过c#将其添加到每次添加的新列中。

在此处输入图片说明

Would something like this work? 这样的事情行吗? (Put in the values you need below, also remember to do appropriate clean up of com objects) (在下面输入您需要的值,还记得对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

Edit: Try the below for updating the entire data source instead of a single series. 编辑:尝试以下更新整个数据源,而不是单个序列。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM