ASP.NET MVC Reporting With RDLC (使用 RDLC 作為報表解決方案)


  1. 說明
    1. 資料連線
    2. 報表建立
    3. 資料集與資料源設計
    4. 報表設計
    5. Controller
    6. View
    7. 驗證結果
  2. Tips
    1. Table Striped
  3. 相關連結

說明如何在 ASP.NET MVC 使用 RDLC 作為報表設計的解決方案,開發可供列印的電子發票、表單等設計以及將提供資料以 Excel, Word 以及 PDF 的方式進行下載。

logo

說明

資料連線

本次使用 AdventureWorksLT2019 做為資料庫,並使用 ASP.NET MVC 5 做為程式框架。


首先使用 EntityFramework 連線資料庫與設定模型,本步驟詳細的設定方式可以參考 ASP.NET MVC EntityFramework Model (Database First)

使用 Nuget 安裝 ReportViewerForMVC,使用的版本為 Armando Aguirre, rsantosdev 所提供的 140.1000.523。

疑?安裝完 ReportViewerForMVC 編譯會報錯?您可能是 web.config 不正確的受害者...

安裝完 ReportViewerForMVC,會在 web.config 新增 Handlers,但不知道為什麼,有時候會重複出現兩筆,這個時候只要註解或移除,僅保持其中一筆就可以了 😀

web.config

<handlers>
  <add name="ReportViewerWebControlHandler" verb="*" 
  path="Reserved.ReportViewerWebControl.axd" preCondition="integratedMode" 
  type="Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=14.0.0.0, Culture=neutral, PublicKeyToken=89845DCD8080CC91" />
</handlers>

報表建立

建立報表資料夾 Report,建立報表 Report.rdlc

點選報表,使用檢視開啟 報表資料,快捷鍵為 Ctrl + Alt + D

資料集與資料源設計

加入資料集,將資料來源新增,使用先前建立的 Entites 連接

取消儲存連線字串

選擇需要使用的資料表、檢視或者是預存程序

儲存以保存資料集。

加入完成的結果:

報表設計

開始設計報表,以 A4 的尺寸進行設計,使用 F4 開啟屬性頁面。

點選報表主體,將尺寸設定為 Width 17cm、Height 25.7cm。

點選空白處,確認 Interactive Size 以及 Page Size Width 為 21cm、Height 為 29.7cm。

其中 Margins Left, Right, Top & Bottom 都是 2cm,也因為 Margins 的關係,主體的尺寸才必須比 A4 的尺寸小。

Size Width Height
主體 17cm 25.7cm
Interactive Size 21cm 29.7cm
Page Size 21cm 29.7cm

在報表中空白處,右鍵加入資料表:

隨興選擇幾個資料欄位,並加入一張圖片點綴 😉

Controller

Controllers/HomeController.cs

public class HomeController : Controller
{
    private readonly AdventureWorksLT2019Entities db = 
        new AdventureWorksLT2019Entities();

    public ActionResult Report()
    {
        ReportViewer reportViewer = new ReportViewer();
        reportViewer.ProcessingMode = ProcessingMode.Local;

        // 設定報表 iFrame Full Width
        reportViewer.SizeToReportContent = true;
        reportViewer.Width = Unit.Percentage(100);
        reportViewer.Height = Unit.Percentage(100);

        // Load Report File From Local Path
        reportViewer.LocalReport.ReportPath = 
            $"{Request.MapPath(Request.ApplicationPath)}Models\\Report.rdlc";

        // Data Loading and Data Source Add
        var datas = db.Customer.Where(
          i => i.CompanyName.StartsWith("A")).ToList();
        reportViewer.LocalReport.DataSources.Add(
            new ReportDataSource("DataSet_Cumstomers", datas)
        );

        return View(reportViewer);
    }
}

View

/Views/Home/Report.cshtml

@model Microsoft.Reporting.WebForms.ReportViewer
@using ReportViewerForMvc

<h2>Report</h2>
@Html.ReportViewer(Model, new { style="width:100%"})

驗證結果

Tips

Table Striped

選取整個資料列後,在屬性對 BackgroundColor 使用運算式進行設定。

運算式的部分必須使用 VB.NET 來編寫,C# 表示遺憾 😑

= IIF(RowNumber(nothing) mod 2 = 0 ,"Transparent", "Silver")

相關連結

ASP.NET MVC 從無到有打造一個應用系統

Visual Studio 入門教學