Visual Studio 2017 中可以使用 RDLC Reporting 插件來設計報表,SAP Crystal Report(水晶報表)的用法與之類似。
步驟一、在 VS 中打開 “工具” 菜單下的 “擴展與更新” 選項,搜索 RDLC Reporting,並安裝:
- Microsoft Rdlc Report Designer for Visual Studio
- Rdlc Designer and projects for ASP.Net and Windows Forms for Reporting Services Report Viewer Control
- Microsoft Reporting Services Projects
- The Microsoft RDL report designer, projects and wizards for creating professional reports.
安裝成功后,新建 WinForm 項目,並添加新項,就可以看到 “報表” 選項了。
步驟二、添加相關的 NuGet 包:Microsoft.ReportingServices.ReportViewerControl.Winforms
步驟三、為項目添加新項,選擇 “報表” 並命名為 Report1.rdlc,然后打開 Report1.rdlc 並添加數據集。
步驟四、打開一個窗體,並在工具箱里的 Microsoft SQL Server 選項下選擇 ReportViewer 控件,添加到 Form2 中。並設置其報表模板。
步驟五、在窗體的加載事件中添加具體的數據綁定邏輯
private void Form2_Load(object sender, EventArgs e) { reportViewer1.LocalReport.ReportEmbeddedResource = "WindowsFormsApp1.Report1.rdlc"; // 包含命名空間和報表文件名稱 DataTable studentDt = new DataTable("DAS_Staff"); studentDt.Columns.Add("StaffID"); studentDt.Columns.Add("StaffFirstName"); studentDt.Columns.Add("StaffLastName"); studentDt.Rows.Add("10001", "Jack", "tt"); studentDt.Rows.Add("10002", "Lucy", "tt"); studentDt.Rows.Add("10003", "Jason", "tt"); studentDt.Rows.Add("10004", "Lili", "tt"); reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("DataSet1", studentDt)); //注:這里數據源名稱要與上面再報表模板中定義的數據源名稱一致。 reportViewer1.RefreshReport(); this.reportViewer1.RefreshReport(); }
最后,運行程序顯示效果如下:
參考資料:
http://shashangka.com/2017/05/17/enable-rdlc-reporting-in-visual-studio-2017
https://www.cnblogs.com/dreamos/p/7599253.html