本文詳細示範如何使用 C# 操作 Excel COM 物件,從建立資料工作表、填入隨機模擬資料,到呼叫 ChartWizard 產生 3D 柱狀圖,並進階設定數據標籤、圖例、標題、軸標題、圖形樣式(圓柱體)等細節。最後提供完整可執行程式碼與多組資料擴充範例。
Excel.Application app = new Excel.Application();
Excel.Workbook wb = (Excel.Workbook)app.Workbooks.Add(Type.Missing);
app.DisplayAlerts = false;
// 刪除多餘的預設工作表與圖表
foreach (Excel.Worksheet ws in wb.Worksheets)
if (ws != app.ActiveSheet) ws.Delete();
foreach (Excel.Chart ch in wb.Charts) ch.Delete();
Excel.Worksheet dataSheet = (Excel.Worksheet)wb.Worksheets.Add(Type.Missing, wb.ActiveSheet, Type.Missing, Type.Missing);
dataSheet.Name = "數據";
Random rnd = new Random();
for (int i = 1; i <= 12; i++)
{
dataSheet.Cells[i, 1] = i + "月";
dataSheet.Cells[i, 2] = rnd.Next(2000).ToString(); // 單組資料
// 若需多組:dataSheet.Cells[i, 3] = rnd.Next(1500).ToString();
}
Excel.Chart chart = (Excel.Chart)wb.Charts.Add(Type.Missing, dataSheet, Type.Missing, Type.Missing);
Excel.Range dataRange = (Excel.Range)dataSheet.Cells[1, 1]; // 起始儲存格
// 使用 ChartWizard 快速產生 3D 群組柱狀圖
chart.ChartWizard(
dataRange.CurrentRegion, // 來源資料區域
Excel.XlChartType.xl3DColumn, // 圖表類型
Type.Missing, // 套用預設圖庫
Excel.XlRowCol.xlColumns, // 以直行為系列
1, // 類別標籤行數
0, // 序列標籤行數
true, // 顯示圖例
"訪問量比較", // 圖表標題
"月份", // X 軸標題
"訪問量", // Y 軸標題
"" // 第二 Y 軸標題
);
chart.Name = "統計";
// 讓每個類別(月份)呈現不同顏色
Excel.ChartGroup grp = (Excel.ChartGroup)chart.ChartGroups(1);
grp.GapWidth = 20;
grp.VaryByCategories = true; // 單系列時有效
// 將柱狀改為圓柱體,並顯示數據標籤
Excel.Series ser = (Excel.Series)grp.SeriesCollection(1);
ser.BarShape = Excel.XlBarShape.xlCylinder;
ser.HasDataLabels = true;
// 圖例置頂、標題加大加陰影加框線
chart.Legend.Position = Excel.XlLegendPosition.xlLegendPositionTop;
chart.ChartTitle.Font.Size = 24;
chart.ChartTitle.Shadow = true;
chart.ChartTitle.Border.LineStyle = Excel.XlLineStyle.xlContinuous;
// 設定 Y 軸標題方向、X 軸字型
Excel.Axis yAxis = (Excel.Axis)chart.Axes(Excel.XlAxisType.xlValue, Excel.XlAxisGroup.xlPrimary);
yAxis.AxisTitle.Orientation = -90;
Excel.Axis xAxis = (Excel.Axis)chart.Axes(Excel.XlAxisType.xlCategory, Excel.XlAxisGroup.xlPrimary);
xAxis.AxisTitle.Font.Name = "MS UI Gothic";
在 LoadData 中新增第三欄資料(如 Cells[i, 3]),圖表自動顯示多系列群組柱狀圖,圖例會切換為系列名稱(而非月份),VaryByCategories 自動失效。
文章末尾提供完整的按鈕點擊事件處理函式 button4_Click,包含 try/finally 資源釋放、DeleteSheet、AddDatasheet、LoadData、CreateChart 等私有方法,可直接複製到 WinForms 專案中執行。
Chart → ChartGroups → SeriesCollection → Series → Points。掌握此流程,即可在 C# 專案中動態產出專業級 Excel 統計圖表,滿足報表自動化需求。