模板中已包含圖表,需動態修改數據源、圖表類型、樣式並另存。
using Excel = Microsoft.Office.Interop.Excel;
using System.Reflection;
public void UpdateChart()
{
Excel.Application excel = null;
Excel._Workbook wb = null;
Excel._Chart chart = null;
Excel.ChartGroup chartGroup = null;
Excel.Series series = null;
object opt = Missing.Value;
try
{
excel = new Excel.Application();
wb = excel.Workbooks.Open(@"z:\Book11.xls", opt, opt, opt, opt, opt, opt, opt, opt, opt, opt, opt, opt);
chart = (Excel._Chart)excel.Charts[1]; // 獲取第一個圖表 sheet
chart.BarShape = Excel.XlBarShape.xlCylinder; // 圓柱狀
chartGroup = (Excel.ChartGroup)chart.ChartGroups(1);
series = (Excel.Series)chartGroup.SeriesCollection(1);
series.Values = 456; // 修改數據值
excel.DisplayAlerts = false;
wb.SaveAs(@"z:\Book2.xls", opt, opt, opt, opt, opt,
Excel.XlSaveAsAccessMode.xlNoChange, opt, opt, opt, opt);
}
catch (Exception ex) { MessageBox.Show(ex.Message); }
finally
{
wb?.Close(opt, opt, opt);
excel?.Workbooks.Close();
excel?.Quit();
Marshal.ReleaseComObject(wb);
Marshal.ReleaseComObject(excel);
wb = null; excel = null;
GC.Collect(); GC.WaitForPendingFinalizers();
}
}
Charts 集合:工作簿級圖表 sheet。ChartGroups:圖表組(如柱狀圖組、折線圖組)。SeriesCollection:數據系列集合,每個 Series 對應一組數據。BarShape:xlCylinder 圓柱、xlCone 圓錐、xlPyramid 金字塔、xlBox 長方體。從零創建圖表:數據填充 → ChartWizard → 系列/軸/圖例/標題精細控制 → 多系列對比。