C# 如何在Excel 動態生成PivotTable

来源:http://www.cnblogs.com/isaboy/archive/2016/04/12/csharp_excel_pivot_table.html
-Advertisement-
Play Games

Excel 中的透視表對於數據分析來說,非常的方便,而且很多業務人員對於Excel的操作也是非常熟悉的,因此用Excel作為分析數據的界面,不失為一種很好的選擇。那麼如何用C#從資料庫中抓取數據,併在Excel 動態生成PivotTable呢?下麵結合實例來說明。 一般來說,資料庫的設計都遵循規範化 ...


  Excel 中的透視表對於數據分析來說,非常的方便,而且很多業務人員對於Excel的操作也是非常熟悉的,因此用Excel作為分析數據的界面,不失為一種很好的選擇。那麼如何用C#從資料庫中抓取數據,併在Excel 動態生成PivotTable呢?下麵結合實例來說明。

一般來說,資料庫的設計都遵循規範化的原則,從而減少數據的冗餘,但是對於數據分析來說,數據冗餘能夠提高數據載入的速度,因此為了演示透視表,這裡現在資料庫中建立一個視圖,將需要分析的數據整合到一個視圖中。如下圖所示:

  數據源準備好後,我們先來建立一個web應用程式,然後用NuGet載入Epplus程式包,如下圖所示:

 在index.aspx前臺頁面中,編寫如下腳本:

 1 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="index.aspx.cs" Inherits="ExcelPivot.Web.index" %>
 2 
 3 <!DOCTYPE html>
 4 <html xmlns="http://www.w3.org/1999/xhtml">
 5 <head runat="server">
 6 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
 7     <title>Excel PivotTable</title>
 8     <link rel="stylesheet" type="text/css" href="css/style.css" />  
 9 </head>
10 <body>
11     <form id="form1" runat="server">
12        <div id="container">
13 
14             <div id="contents">
15 
16                 <div id="post">
17                     <header>
18                         <h1> Excel PivotTable </h1>
19                     </header>
20                     <div id="metro-array" style="display: inline-block;">
21                         <div style="width: 230px; height: 230px; float: left; ">
22 
23                             <a class="metro-tile" style="cursor: pointer; width: 230px; height: 110px; display: block; background-color:#ff0000; color: #fff; margin-bottom: 10px;">
24                                 
25                                  <input type="button" runat="server" id="Button1" name="btn1" value="回款情況分析" onserverclick="btn1_ServerClick"  
26                                                    style="background-color:transparent; color:white; font-size:16px;float:left; border:0; width:230px; height:110px; cursor:pointer;"/>
27                             
28                             </a>
29 
30                             <a class="metro-tile" style="cursor: pointer; width: 230px; height: 110px; display: block; background-color:#ff6a00; color: #fff;">
31                                  <input type="button" runat="server" id="Button2" name="btn1" value="sampe1" onserverclick="btn1_ServerClick"  
32                                                    style="background-color:transparent; color:white; font-size:16px;float:left; border:0; width:230px; height:110px; cursor:pointer;"/>
33                             </a>
34                         </div>
35 
36                         <div style="width: 230px; height: 230px; float: left; margin-left: 10px">
37 
38                             <a class="metro-tile" style="cursor: pointer; width: 230px; height: 230px; display: block; background-color:#ffd800; color: #fff">
39                                  <input type="button" runat="server" id="btn1" name="btn1" value="sampe1" onserverclick="btn1_ServerClick"  
40                                                    style="background-color:transparent; color:white; font-size:16px;float:left; border:0; width:230px; height:230px; cursor:pointer;"/>
41                             </a>
42 
43                         </div>
44 
45                         <div style="width: 230px; height: 230px; float: left; margin-left: 10px">
46 
47                             <a class="metro-tile" style="cursor: pointer; width: 230px; height: 110px; display: block; background-color:#0094ff; color: #fff; margin-bottom: 10px;">
48                                  <input type="button" runat="server" id="Button3" name="btn1" value="sampe1" onserverclick="btn1_ServerClick"  
49                                                    style="background-color:transparent; color:white; font-size:16px;float:left; border:0; width:230px; height:110px; cursor:pointer;"/>
50                             </a>
51 
52                             <a class="metro-tile" style="cursor: pointer; width: 110px; height: 110px; margin-right: 10px; display: block; float: left; background-color: #4800ff; color: #fff;">
53                                  <input type="button" runat="server" id="Button4" name="btn1" value="sampe1" onserverclick="btn1_ServerClick"  
54                                                    style="background-color:transparent; color:white; font-size:16px;float:left; border:0; width:110px; height:110px; cursor:pointer;"/>
55                             </a>
56 
57                             <a class="metro-tile" style="cursor: pointer; width: 110px; height: 110px; display: block; background-color: #b200ff; float: right; color: #fff;">
58                                  <input type="button" runat="server" id="Button5" name="btn1" value="sampe1" onserverclick="btn1_ServerClick"  
59                                                    style="background-color:transparent; color:white; font-size:16px;float:left; border:0; width:110px; height:110px; cursor:pointer;"/>
60                             </a>
61                         </div>
62 
63                     </div>
64                 </div>
65 
66             </div>
67         </div>
68     </form>
69 </body>
70     <script src="js/tileJs.js" type="text/javascript"></script>
71 </html>

其中 TileJs是一個開源的構建類似win8 Metro風格的javascript庫。

編寫後臺腳本:

  1 using System;
  2 using System.Collections.Generic;
  3 using System.Linq;
  4 using System.Web;
  5 using System.Web.UI;
  6 using System.Web.UI.WebControls;
  7 using OfficeOpenXml;
  8 using OfficeOpenXml.Table;
  9 using OfficeOpenXml.ConditionalFormatting;
 10 using OfficeOpenXml.Style;
 11 using OfficeOpenXml.Utils;
 12 using OfficeOpenXml.Table.PivotTable;
 13 using System.IO;
 14 using System.Data.SqlClient;
 15 using System.Data;
 16 namespace ExcelPivot.Web
 17 {
 18     public partial class index : System.Web.UI.Page
 19     {
 20         protected void Page_Load(object sender, EventArgs e)
 21         {
 22 
 23         }
 24         private DataTable getDataSource()
 25         {
 26             //createDataTable();
 27             //return ProductInfo;
 28 
 29             SqlConnection conn = new SqlConnection();
 30             conn.ConnectionString = "Data Source=.;Initial Catalog=olap;Persist Security Info=True;User ID=sa;Password=sa";
 31             conn.Open();
 32 
 33             SqlDataAdapter ada = new SqlDataAdapter("select * from v_pm_olap_test", conn);
 34             DataSet ds = new DataSet();
 35             ada.Fill(ds);
 36 
 37             return ds.Tables[0];
 38 
 39 
 40 
 41         }
 42       
 43         protected void btn1_ServerClick(object sender, EventArgs e)
 44         {
 45             try
 46             {
 47                 DataTable table = getDataSource();
 48                 string path = "_demo_" + System.Guid.NewGuid().ToString().Replace("-", "_") + ".xls";
 49                 //string path = "_demo.xls";
 50                 FileInfo fileInfo = new FileInfo(path);
 51                 var excel = new ExcelPackage(fileInfo);
 52 
 53                 var wsPivot = excel.Workbook.Worksheets.Add("Pivot");
 54                 var wsData = excel.Workbook.Worksheets.Add("Data");
 55                 wsData.Cells["A1"].LoadFromDataTable(table, true, OfficeOpenXml.Table.TableStyles.Medium6);
 56                 if (table.Rows.Count != 0)
 57                 {
 58                     foreach (DataColumn col in table.Columns)
 59                     {
 60                      
 61                         if (col.DataType == typeof(System.DateTime))
 62                         {
 63                             var colNumber = col.Ordinal + 1;
 64                             var range = wsData.Cells[2, colNumber, table.Rows.Count + 1, colNumber];
 65                             range.Style.Numberformat.Format = "yyyy-MM-dd";
 66                         }
 67                         else
 68                         {
 69 
 70                         }
 71                     }
 72                 }
 73 
 74                 var dataRange = wsData.Cells[wsData.Dimension.Address.ToString()];
 75                 dataRange.AutoFitColumns();
 76                 var pivotTable = wsPivot.PivotTables.Add(wsPivot.Cells["A1"], dataRange, "Pivot");
 77                 pivotTable.MultipleFieldFilters = true;
 78                 pivotTable.RowGrandTotals = true;
 79                 pivotTable.ColumGrandTotals = true;
 80                 pivotTable.Compact = true;
 81                 pivotTable.CompactData = true;
 82                 pivotTable.GridDropZones = false;
 83                 pivotTable.Outline = false;
 84                 pivotTable.OutlineData = false;
 85                 pivotTable.ShowError = true;
 86                 pivotTable.ErrorCaption = "[error]";
 87                 pivotTable.ShowHeaders = true;
 88                 pivotTable.UseAutoFormatting = true;
 89                 pivotTable.ApplyWidthHeightFormats = true;
 90                 pivotTable.ShowDrill = true;
 91                 pivotTable.FirstDataCol = 3;
 92                 //pivotTable.RowHeaderCaption = "行";
 93 
 94                 //row field
 95                 var field004 = pivotTable.Fields["銷售客戶經理"];
 96                 pivotTable.RowFields.Add(field004);
 97 
 98                 var field001 = pivotTable.Fields["項目簡稱"];
 99                 pivotTable.RowFields.Add(field001);
100                 //field001.ShowAll = false;
101 
102                 //column field
103                 var field002 = pivotTable.Fields[""];
104                 pivotTable.ColumnFields.Add(field002);
105                 field002.Sort = OfficeOpenXml.Table.PivotTable.eSortType.Ascending;
106                 var field005 = pivotTable.Fields[""];
107                 pivotTable.ColumnFields.Add(field005);
108                 field005.Sort = OfficeOpenXml.Table.PivotTable.eSortType.Ascending;
109 
110                 //data field
111                 var field003 = pivotTable.Fields["回款金額"];
112                 field003.Sort = OfficeOpenXml.Table.PivotTable.eSortType.Descending;
113                 pivotTable.DataFields.Add(field003);
114 
115                 pivotTable.RowGrandTotals = false;
116                 pivotTable.ColumGrandTotals = false;
117               
118                 //save file
119                 excel.Save();
120                 //open excel file
121                 string file = @"C:\Windows\explorer.exe";
122                 System.Diagnostics.Process.Start(file, path);
123 
124             }
125             catch (Exception ex)
126             {
127               Response.Write(ex.Message);
128             }
129         }
130     }
131 }

  編譯運行,如下圖所示:

 單擊 [回款情況分析],稍等片刻,會打開Excel,並自動生成透視表,如下圖所示:


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 介面 什麼是介面? 介面代表一種能力,和抽象類類似但比抽象類的抽象程度更高! 介面的定義: 1 public interface IEat//定義一個介面 2 { 3 void Eat(string food);//為該介面定義一種能力 4 } 從上邊的例子中我們可以看到,介面中的方法是沒有方法體的 ...
  • 預設情況下,當EF調用SaveChanges()時,會把生成的所有SQL命令“包”到一個“事務(transaction)”中,只要有一個數據更新操作失敗,整個事務將回滾。 在多數情況下,如果你總在數據更新操作代碼中使用一個而不是多個DbContext對象,並且只是在最後調用一次SaveChanges ...
  • 上一篇《分享在winform下實現模塊化插件編程》已經實現了模塊化編程,但我認為不夠完美,存在以下幾個問題: 1.IAppContext中的CreatePlugInForm方法只能依據完整的窗體類型名稱formTypeName來動態創建窗體對象,調用不夠方便,且該方法創建的窗體不受各模塊註冊窗體類型 ...
  • 1 public ActionResult A(string title) 2 { 3 return Redirect("B"+((String.IsNullOrEmpty(title))?"":"?title="+title.ToString())); 4 } 5 public ActionRes ...
  • 返回布爾值,判斷集合中是否有元素滿足某一條件。 source code: IEnumerable<string> str = new List<string> { "asdf","fgsdfg","tyuiu","ryury","ituyitu" }; if (str.Any(x => x.Ends ...
  • 需要擴展IQueryable<T>,參數包括一個DateTime類型的屬性、開始日期、截止日期。 現在可以篩選滿足某個日期範圍內的集合。比如: ...
  • 最近剛剛做了一個刮刮卡的游戲,現在給大家分享一下製作的思路。先給大家看下效果圖。 頁面是直接在網上找的就不過多介紹,大家可以直接百度。當用戶進入頁面的時候,後臺獲取用戶mac地址並存入資料庫作為用戶的標誌,以便於用戶第二天進入時刷新抽獎次數。 抽獎結果這一塊是用戶進入頁面直接生成一個隨機數並與資料庫 ...
  • 幀頭 UTC時間 狀態 緯度 北緯/南緯 經度 東經/西經 速度 $GPRMC hhmmss.sss A/V ddmm.mmmm N/S dddmm.mmmm E/W 節 方位角 UTC日期 磁偏角 磁偏角方向 模式 校驗 回車換行 度 ddmmyy 000 - 180 E/W A/D/E/N *h ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...