首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 操作 Excel 生成報表(二):操作現有圖表並導出

     編輯:關於C語言

場景

模板中已包含圖表,需動態修改數據源、圖表類型、樣式並另存。

核心代碼


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 → 系列/軸/圖例/標題精細控制 → 多系列對比。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved