使用C#實(shí)現(xiàn)在Excel中創(chuàng)建和配置數(shù)據(jù)透視表
在數(shù)據(jù)分析和業(yè)務(wù)報(bào)告場(chǎng)景中,數(shù)據(jù)透視表(Pivot Table)是一種強(qiáng)大的數(shù)據(jù)匯總工具。它能夠快速對(duì)大量數(shù)據(jù)進(jìn)行分類、匯總和分析,幫助用戶從不同維度洞察數(shù)據(jù)規(guī)律。
對(duì)于 .NET 開(kāi)發(fā)者而言,在某些場(chǎng)景下需要通過(guò)代碼自動(dòng)生成包含數(shù)據(jù)透視表的 Excel 報(bào)表。例如:
- 自動(dòng)化生成銷售分析報(bào)表
- 批量處理業(yè)務(wù)數(shù)據(jù)匯總
- 動(dòng)態(tài)創(chuàng)建財(cái)務(wù)分析報(bào)告
本文將介紹如何使用 C# 在 Excel 工作表中創(chuàng)建和配置數(shù)據(jù)透視表,包括數(shù)據(jù)源設(shè)置、字段布局和樣式美化等關(guān)鍵步驟。
環(huán)境準(zhǔn)備
首先需要在項(xiàng)目中添加 Spire.XLS for .NET 庫(kù)??梢酝ㄟ^(guò) NuGet 包管理器安裝:
Install-Package Spire.XLS
核心實(shí)現(xiàn)
創(chuàng)建工作簿和基礎(chǔ)數(shù)據(jù)
創(chuàng)建數(shù)據(jù)透視表之前,需要先準(zhǔn)備源數(shù)據(jù)。以下代碼演示如何創(chuàng)建一個(gè)包含產(chǎn)品銷售數(shù)據(jù)的工作表:
using Spire.Xls; // 創(chuàng)建工作簿實(shí)例 Workbook workbook = new Workbook(); // 獲取第一個(gè)工作表 Worksheet sheet = workbook.Worksheets[0]; // 設(shè)置列標(biāo)題 sheet.Range["A1"].Value = "Product"; sheet.Range["B1"].Value = "Month"; sheet.Range["C1"].Value = "Count"; // 填充產(chǎn)品數(shù)據(jù) sheet.Range["A2"].Value = "SpireDoc"; sheet.Range["A3"].Value = "SpireDoc"; sheet.Range["A4"].Value = "SpireXls"; sheet.Range["A5"].Value = "SpireDoc"; sheet.Range["A6"].Value = "SpireXls"; sheet.Range["A7"].Value = "SpireXls"; // 填充月份數(shù)據(jù) sheet.Range["B2"].Value = "January"; sheet.Range["B3"].Value = "February"; sheet.Range["B4"].Value = "January"; sheet.Range["B5"].Value = "January"; sheet.Range["B6"].Value = "February"; sheet.Range["B7"].Value = "February"; // 填充數(shù)量數(shù)據(jù) sheet.Range["C2"].Value = "10"; sheet.Range["C3"].Value = "15"; sheet.Range["C4"].Value = "9"; sheet.Range["C5"].Value = "7"; sheet.Range["C6"].Value = "8"; sheet.Range["C7"].Value = "10";
這段代碼創(chuàng)建了一個(gè)簡(jiǎn)單的銷售數(shù)據(jù)表,包含產(chǎn)品名稱、月份和銷售數(shù)量三個(gè)字段。在實(shí)際應(yīng)用中,這些數(shù)據(jù)通常來(lái)自數(shù)據(jù)庫(kù)或其他數(shù)據(jù)源。
創(chuàng)建數(shù)據(jù)透視表緩存
數(shù)據(jù)透視表需要基于一個(gè)數(shù)據(jù)緩存(PivotCache)來(lái)工作。緩存存儲(chǔ)了源數(shù)據(jù)的副本,用于提高性能:
// 定義數(shù)據(jù)源范圍 CellRange dataRange = sheet.Range["A1:C7"]; // 創(chuàng)建數(shù)據(jù)透視表緩存 PivotCache cache = workbook.PivotCaches.Add(dataRange);
PivotCache 對(duì)象負(fù)責(zé)管理數(shù)據(jù)透視表的源數(shù)據(jù)。通過(guò)將數(shù)據(jù)范圍傳遞給緩存,可以在后續(xù)的數(shù)據(jù)透視表操作中引用這份數(shù)據(jù)。
添加數(shù)據(jù)透視表到工作表
創(chuàng)建緩存后,就可以在工作表上添加數(shù)據(jù)透視表了:
// 在工作表的 E10 單元格位置添加數(shù)據(jù)透視表
PivotTable pt = sheet.PivotTables.Add("Pivot Table", sheet.Range["E10"], cache);
這里指定了三個(gè)參數(shù):
"Pivot Table":數(shù)據(jù)透視表的名稱sheet.Range["E10"]:數(shù)據(jù)透視表左上角的起始位置cache:之前創(chuàng)建的數(shù)據(jù)緩存
配置行字段
行字段決定了數(shù)據(jù)在垂直方向上的分組方式。可以將多個(gè)字段添加到行區(qū)域來(lái)實(shí)現(xiàn)多級(jí)分組:
// 將 Product 字段添加到行區(qū)域 PivotField pf = pt.PivotFields["Product"] as PivotField; pf.Axis = AxisTypes.Row; // 將 Month 字段添加到行區(qū)域 PivotField pf2 = pt.PivotFields["Month"] as PivotField; pf2.Axis = AxisTypes.Row;
通過(guò)設(shè)置 Axis 屬性為 AxisTypes.Row,可以將字段放置在行區(qū)域。這樣數(shù)據(jù)會(huì)先按產(chǎn)品分組,然后在每個(gè)產(chǎn)品下再按月份分組。
配置數(shù)據(jù)字段
數(shù)據(jù)字段用于對(duì)數(shù)值進(jìn)行匯總計(jì)算。常見(jiàn)的匯總方式包括求和、計(jì)數(shù)、平均值等:
// 將 Count 字段添加到數(shù)據(jù)區(qū)域,使用求和方式 pt.DataFields.Add(pt.PivotFields["Count"], "SUM of Count", SubtotalTypes.Sum);
這行代碼的含義是:
pt.PivotFields["Count"]:選擇要匯總的字段"SUM of Count":數(shù)據(jù)字段的顯示名稱SubtotalTypes.Sum:匯總類型為求和
除了 Sum 之外,還可以使用 Count、Average、Max、Min 等多種匯總類型。
設(shè)置樣式和自動(dòng)調(diào)整
為了提高可讀性,可以為數(shù)據(jù)透視表應(yīng)用內(nèi)置樣式,并自動(dòng)調(diào)整列寬:
// 應(yīng)用內(nèi)置樣式 pt.BuiltInStyle = PivotBuiltInStyles.PivotStyleMedium12; // 計(jì)算數(shù)據(jù)透視表數(shù)據(jù) pt.CalculateData(); // 自動(dòng)調(diào)整列寬以適應(yīng)內(nèi)容 sheet.AutoFitColumn(5); sheet.AutoFitColumn(6);
CalculateData() 方法確保數(shù)據(jù)透視表在保存前完成計(jì)算。AutoFitColumn() 方法根據(jù)內(nèi)容自動(dòng)調(diào)整列寬,使輸出更加美觀。
保存文件
最后,將生成的工作簿保存到文件:
String result = "CreatePivotTable_output.xlsx"; // 以 Excel 2010 格式保存 workbook.SaveToFile(result, ExcelVersion.Version2010); // 釋放資源 workbook.Dispose();
完整示例
以下是完整的代碼示例:
using System;
using Spire.Xls;
class Program
{
static void Main()
{
// 創(chuàng)建工作簿
Workbook workbook = new Workbook();
// 獲取第一個(gè)工作表
Worksheet sheet = workbook.Worksheets[0];
// 設(shè)置列標(biāo)題
sheet.Range["A1"].Value = "Product";
sheet.Range["B1"].Value = "Month";
sheet.Range["C1"].Value = "Count";
// 填充示例數(shù)據(jù)
sheet.Range["A2"].Value = "SpireDoc";
sheet.Range["A3"].Value = "SpireDoc";
sheet.Range["A4"].Value = "SpireXls";
sheet.Range["A5"].Value = "SpireDoc";
sheet.Range["A6"].Value = "SpireXls";
sheet.Range["A7"].Value = "SpireXls";
sheet.Range["B2"].Value = "January";
sheet.Range["B3"].Value = "February";
sheet.Range["B4"].Value = "January";
sheet.Range["B5"].Value = "January";
sheet.Range["B6"].Value = "February";
sheet.Range["B7"].Value = "February";
sheet.Range["C2"].Value = "10";
sheet.Range["C3"].Value = "15";
sheet.Range["C4"].Value = "9";
sheet.Range["C5"].Value = "7";
sheet.Range["C6"].Value = "8";
sheet.Range["C7"].Value = "10";
// 創(chuàng)建數(shù)據(jù)透視表緩存
CellRange dataRange = sheet.Range["A1:C7"];
PivotCache cache = workbook.PivotCaches.Add(dataRange);
// 添加數(shù)據(jù)透視表
PivotTable pt = sheet.PivotTables.Add("Pivot Table", sheet.Range["E10"], cache);
// 配置行字段
PivotField pf = pt.PivotFields["Product"] as PivotField;
pf.Axis = AxisTypes.Row;
PivotField pf2 = pt.PivotFields["Month"] as PivotField;
pf2.Axis = AxisTypes.Row;
// 配置數(shù)據(jù)字段
pt.DataFields.Add(pt.PivotFields["Count"], "SUM of Count", SubtotalTypes.Sum);
// 設(shè)置樣式
pt.BuiltInStyle = PivotBuiltInStyles.PivotStyleMedium12;
// 計(jì)算數(shù)據(jù)并調(diào)整列寬
pt.CalculateData();
sheet.AutoFitColumn(5);
sheet.AutoFitColumn(6);
// 保存文件
workbook.SaveToFile("CreatePivotTable_output.xlsx", ExcelVersion.Version2010);
workbook.Dispose();
Console.WriteLine("數(shù)據(jù)透視表創(chuàng)建成功!");
}
}
生成結(jié)果預(yù)覽

實(shí)用技巧
更改字段布局
除了行字段和數(shù)據(jù)字段,還可以將字段添加到列區(qū)域或篩選區(qū)域:
// 將字段添加到列區(qū)域 PivotField columnField = pt.PivotFields["Month"] as PivotField; columnField.Axis = AxisTypes.Column; // 將字段添加到篩選區(qū)域 PivotField filterField = pt.PivotFields["Product"] as PivotField; filterField.Axis = AxisTypes.Page;
使用不同的匯總方式
根據(jù)分析需求,可以選擇不同的匯總類型:
// 計(jì)數(shù) pt.DataFields.Add(pt.PivotFields["Count"], "Count", SubtotalTypes.Count); // 平均值 pt.DataFields.Add(pt.PivotFields["Count"], "Average", SubtotalTypes.Average); // 最大值 pt.DataFields.Add(pt.PivotFields["Count"], "Max", SubtotalTypes.Max);
自定義數(shù)據(jù)透視表選項(xiàng)
可以進(jìn)一步配置數(shù)據(jù)透視表的顯示選項(xiàng):
// 顯示經(jīng)典數(shù)據(jù)透視表布局 pt.ShowClassicPivotTableLayout = true; // 禁用字段列表 pt.FieldPrintOptions.ShowFieldList = false;
結(jié)論
本文介紹了如何使用 C# 在 Excel 中創(chuàng)建數(shù)據(jù)透視表。通過(guò)合理配置數(shù)據(jù)源、字段布局和樣式選項(xiàng),可以快速生成專業(yè)的數(shù)據(jù)分析報(bào)表。
掌握這些技術(shù)后,你可以:
- 擴(kuò)展為從數(shù)據(jù)庫(kù)讀取真實(shí)業(yè)務(wù)數(shù)據(jù)
- 添加更多字段和更復(fù)雜的分組邏輯
- 應(yīng)用條件格式增強(qiáng)可視化效果
- 批量生成多張數(shù)據(jù)透視表進(jìn)行分析
數(shù)據(jù)透視表是 Excel 數(shù)據(jù)分析的核心功能之一,將其集成到自動(dòng)化流程中可以大大提高報(bào)表生成效率。
到此這篇關(guān)于使用C#實(shí)現(xiàn)在Excel中創(chuàng)建和配置數(shù)據(jù)透視表的文章就介紹到這了,更多相關(guān)C# Excel創(chuàng)建數(shù)據(jù)透視表內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C#中實(shí)現(xiàn)可變參數(shù)實(shí)例
這篇文章主要介紹了C#中實(shí)現(xiàn)可變參數(shù)實(shí)例,本文演示使用params 實(shí)現(xiàn)可變數(shù)量的參數(shù),并且這些參數(shù)的類型可以不同,需要的朋友可以參考下2015-01-01
C#?使用PrintDocument類打印標(biāo)簽的方法
本文介紹打印機(jī)初步配置,以及實(shí)現(xiàn)方法,標(biāo)簽主要展示資產(chǎn)基本信息以及二維碼,對(duì)C#?使用PrintDocument類打印標(biāo)簽的詳細(xì)過(guò)程感興趣的朋友一起看看吧2022-04-04
C#實(shí)現(xiàn)文件與Base64的相互轉(zhuǎn)換
本文主要介紹了C#實(shí)現(xiàn)文件與Base64的相互轉(zhuǎn)換,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2023-06-06
C#實(shí)現(xiàn)調(diào)用迅雷下載的方法
這篇文章主要介紹了C#實(shí)現(xiàn)調(diào)用迅雷下載的方法,非常實(shí)用的一個(gè)技巧,對(duì)于進(jìn)行C#程序設(shè)計(jì)有很好的借鑒價(jià)值,需要的朋友可以參考下2014-08-08
C#實(shí)現(xiàn)利用泛型將DataSet轉(zhuǎn)為Model的方法
這篇文章主要介紹了C#實(shí)現(xiàn)利用泛型將DataSet轉(zhuǎn)為Model的方法,實(shí)例分析了C#泛型的相關(guān)使用技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-07-07
MVVM簡(jiǎn)化的Messager類實(shí)例代碼
這篇文章主要給大家介紹了關(guān)于MVVM簡(jiǎn)化的Messager類的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2018-06-06

