首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> 關於.NET

Reporting Services 動態切換圖表類型:修改 RDLC XML 實現柱狀圖/圓餅圖切換

     編輯:關於.NET

需求背景

使用者需在報表中動態切換圖表類型 (如柱狀圖 ↔ 圓餅圖)。Reporting Services API 無直接支援,解決方案:執行期修改 RDLC XML。

準備工作

  1. 資料來源:Northwind 資料庫 + 儲存程序 SaleReportByCountry (依國家統計銷售額)
  2. 專案類型:VS2008 報表應用程式 (本地報表 .rdlc)
  3. 建立 DataSet、TableAdapter、ReportViewer 控制項

建立基礎報表

  1. 拖曳 圖表 至報表主體
  2. 預設類型:柱狀圖
  3. 拖放欄位:Category=Country, Data=SaleAmount
  4. 執行確認資料顯示正常

核心技術:RDLC 即 XML

.rdlc 本質是 XML 檔案。圖表類型儲存在:


/Report/Body/ReportItems/Chart[@Name='chart1']/Type

動態切換實作

準備動態報表檔案

  • 複製原 SalesReport.rdlc 為 DynamicSalesReport.rdlc
  • 設定屬性:複製到輸出目錄 = 永遠複製 (執行期可讀寫)

切換程式碼


private void ChangeChartType(string type)  // "Column" 或 "Pie"
{
    XmlDocument doc = new XmlDocument();
    doc.Load("DynamicSalesReport.rdlc");
    
    XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
    nsmgr.AddNamespace("x", "https://schemas.microsoft.com/sqlserver/reporting/2005/01/reportdefinition");
    nsmgr.AddNamespace("rd", "https://schemas.microsoft.com/SQLServer/reporting/reportdesigner");
    
    // 修改圖表類型節點
    XmlNode chartTypeNode = doc.SelectSingleNode(
        "/x:Report/x:Body/x:ReportItems/x:Chart[@Name='chart1']/x:Type", nsmgr);
    chartTypeNode.InnerText = type;
    
    // 存入記憶體流
    MemoryStream ms = new MemoryStream();
    doc.Save(ms);
    ms.Position = 0;
    
    // 重新載入報表定義
    reportViewer1.Reset();  // 必須 Reset 才生效
    reportViewer1.LocalReport.LoadReportDefinition(ms);
    
    // 重新繫結資料 (LoadReportDefinition 會清除資料來源)
    saleReportByCountryTableAdapter1.Fill(
        northwindDataSet1.SaleReportByCountry, 
        new DateTime(1996, 1, 1), new DateTime(1998, 1, 1));
    
    ReportDataSource ds = new ReportDataSource(
        "NorthwindDataSet_SaleReportByCountry", 
        northwindDataSet1.SaleReportByCountry);
    
    reportViewer1.LocalReport.DataSources.Clear();
    reportViewer1.LocalReport.DataSources.Add(ds);
    reportViewer1.RefreshReport();
    
    ms.Close();
}

按鈕事件


private void btnColumnChart_Click(object sender, EventArgs e)
    => ChangeChartType("Column");

private void btnPieChart_Click(object sender, EventArgs e)
    => ChangeChartType("Pie");

關鍵點總結

關鍵步驟說明
命名空間管理RDLC 有預設命名空間,XPath 必須註冊前綴
XPath 定位精確定位 Chart[@Name='chart1']/Type 節點
MemoryStream避免檔案鎖定,記憶體中修改後直接載入
Reset()ReportViewer.Reset() 清除舊定義,LoadReportDefinition 才生效
重新繫結資料LoadReportDefinition 會清除 DataSources,必須重新加入

支援的圖表類型

常用類型字串:Column、Bar、Pie、Line、Area、Doughnut、Point 等 (需符合 RS 圖表類型常數)。

效能考量

  • XML 修改極快 (毫秒級)
  • 適合使用者互動式切換
  • 大型報表建議快取常用類型的修改版 XML

總結

透過「RDLC 即 XML」特性,配合 XmlDocument、MemoryStream、ReportViewer.Reset/LoadReportDefinition,輕鬆實現圖表類型動態切換。此技巧同樣適用於動態修改報表標題、欄位可見性、樣式等屬性。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved