`:表頭列 + 每一列資料 + 總計列/欄(選配)。
完整 ASP.NET Web Forms 實作 (C#)
public partial class CrossTabReport : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) RenderCrossTab();
}
private void RenderCrossTab()
{
// 1. 取得原始資料 (範例模擬)
var dt = GetSourceData();
// 2. 蒐集維度鍵值 (保持順序用 List + Contains)
var rowKeys = new List();
var colKeys = new List();
var dataMap = new Dictionary();
foreach (DataRow dr in dt.Rows)
{
string rowKey = dr["Category"].ToString();
string colKey = dr["Month"].ToString();
decimal val = Convert.ToDecimal(dr["Amount"]);
if (!rowKeys.Contains(rowKey)) rowKeys.Add(rowKey);
if (!colKeys.Contains(colKey)) colKeys.Add(colKey);
string key = rowKey + "|" + colKey;
dataMap[key] = dataMap.GetValueOrDefault(key) + val; // 彙總
}
// 3. 建立 Table 控制項
var table = new Table { CssClass = "cross-tab", GridLines = GridLines.Both };
// 3.1 表頭列
var headerRow = new TableRow { TableSection = TableRowSection.TableHeader };
headerRow.Cells.Add(new TableHeaderCell { Text = "類別 \\ 月份" });
foreach (var col in colKeys)
headerRow.Cells.Add(new TableHeaderCell { Text = col });
headerRow.Cells.Add(new TableHeaderCell { Text = "小計" });
table.Rows.Add(headerRow);
// 3.2 資料列 + 列小計
foreach (var row in rowKeys)
{
var tr = new TableRow();
tr.Cells.Add(new TableCell { Text = row, Font = { Bold = true } });
decimal rowTotal = 0;
foreach (var col in colKeys)
{
string key = row + "|" + col;
decimal val = dataMap.GetValueOrDefault(key);
rowTotal += val;
tr.Cells.Add(new TableCell { Text = val > 0 ? val.ToString("N0") : "" });
}
tr.Cells.Add(new TableCell { Text = rowTotal.ToString("N0"), Font = { Bold = true } });
table.Rows.Add(tr);
}
// 3.3 欄小計 + 總計
var totalRow = new TableRow { TableSection = TableRowSection.TableFooter };
totalRow.Cells.Add(new TableHeaderCell { Text = "總計" });
decimal grandTotal = 0;
foreach (var col in colKeys)
{
decimal colTotal = rowKeys.Sum(r => dataMap.GetValueOrDefault(r + "|" + col));
grandTotal += colTotal;
totalRow.Cells.Add(new TableHeaderCell { Text = colTotal.ToString("N0") });
}
totalRow.Cells.Add(new TableHeaderCell { Text = grandTotal.ToString("N0") });
table.Rows.Add(totalRow);
// 4. 輸出到 PlaceHolder
phReport.Controls.Add(table);
}
// 模擬資料來源
private DataTable GetSourceData()
{
var dt = new DataTable();
dt.Columns.Add("Category", typeof(string));
dt.Columns.Add("Month", typeof(string));
dt.Columns.Add("Amount", typeof(decimal));
string[] cats = { "筆記型電腦", "桌上型電腦", "平板", "手機" };
string[] months = { "1月", "2月", "3月", "4月" };
var rand = new Random();
foreach (var c in cats)
foreach (var m in months)
dt.Rows.Add(c, m, rand.Next(10, 500));
return dt;
}
}
.aspx 頁面配置
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="CrossTabReport.aspx.cs" Inherits="Demo.CrossTabReport" %>
<html><body>
<form runat="server">
<h2>產品類別 x 月份 銷售交叉表</h2>
<asp:PlaceHolder ID="phReport" runat="server" />
</form>
<style>
.cross-tab { border-collapse: collapse; width: 100%; font-family: 'Microsoft JhengHei', sans-serif; }
.cross-tab th, .cross-tab td { border: 1px solid #ddd; padding: 8px; text-align: center; }
.cross-tab th { background: #2c3e50; color: white; }
.cross-tab tr:nth-child(even) td { background: #f8f9fa; }
.cross-tab tfoot th { background: #e8f5e9; }
</style>
</body></html>
進階擴充功能
1. 多層級列/欄標頭 (多維度)
// Key 結構改為 Tuple 或自訂類別
var key = (Region, Category, Month);
// 表頭需渲染多行 ,使用 colspan/rowspan 合併儲存格
2. 支援多種彙總函數 (Sum, Avg, Count, Min, Max)
enum AggFunc { Sum, Avg, Count, Min, Max }
// 儲存 List 再計算,或線上演算法 (Welford 算法求平均)
3. 客戶端互動 (排序、篩選、鑽取)
- 整合 **DataTables.js** 或 **AG Grid** 取得完整試算表體驗。
- 或輸出 JSON 供前端 Vue/React 組件渲染。
4. 匯出 Excel (EPPlus / ClosedXML)
using (var pkg = new ExcelPackage())
{
var ws = pkg.Workbook.Worksheets.Add("CrossTab");
// 寫入標頭、資料、公式
ws.Cells["A1"].LoadFromDataTable(dt, true); // 或手寫 PivotTable
Response.BinaryWrite(pkg.GetAsByteArray());
}
效能考量
| 資料筆數 | 列數 | 欄數 | 建議做法 |
|----------|------|------|----------|
| < 10,000 | < 50 | < 20 | 記憶體 Dictionary 即時彙總 (本文做法) |
| 10K ~ 1M | < 100 | < 50 | SQL `PIVOT` / `GROUP BY CUBE` 由資料庫完成 |
| > 1M | 大 | 大 | OLAP Cube (SSAS) / ClickHouse / Apache Druid |
總結
雙維度交叉表的核心在於 **「鍵值索引 + 矩陣渲染」**。掌握此模式,即可靈活應對各類報表需求。小資料量用記憶體 Dictionary 快速原型;大資料量下推至資料庫層;展示層則交給專業元件 (DataTables, AG Grid, Excel) 處理互動與匯出。
copyright ©
萬盛學電腦網 all rights reserved