方案優勢
- Excel 安裝率高,客戶端直接打開打印,無需 PDF 閱讀器。
- 微軟官方 COM 接口穩定、功能全、品牌可信。
- 代碼靈活控制數據、樣式、圖表細節,優於定製報表控件。
引用與核心對象
// 添加引用:Microsoft Excel 14.0/15.0/16.0 Object Library
using Excel = Microsoft.Office.Interop.Excel;
Excel.Application ThisApplication;
Excel.Workbooks ThisWorkbooks;
Excel._Workbook ThisWorkbook;
Excel.Worksheet XlSheet;
刪除默認多餘 Sheet
void DeleteExtraSheets()
{
foreach (Excel.Worksheet ws in ThisWorkbook.Worksheets)
if (ws != ThisApplication.ActiveSheet) ws.Delete();
foreach (Excel.Chart cht in ThisWorkbook.Charts) cht.Delete();
}
添加數據 Sheet
void AddDataSheet()
{
XlSheet = (Excel.Worksheet)ThisWorkbook.Worksheets.Add(Missing.Value, ThisWorkbook.ActiveSheet, Missing.Value, Missing.Value);
XlSheet.Name = "數據";
}
生成測試數據
void LoadData()
{
Random r = new Random();
for (int i = 1; i <= 12; i++)
{
XlSheet.Cells[i, 1] = i + "月";
XlSheet.Cells[i, 2] = r.Next(2000).ToString();
}
}
系列規劃
- 本文:準備工作、數據 Sheet、測試數據。
- 創建 Chart、ChartWizard、基礎樣式。
- ChartWizard 詳細參數、軸設置、保存導出。
- 多系列數據、VaryByCategories 行為差異。
- 完整代碼總覽、效果截圖。