close
於WPF視窗程式內加入報表(ReportViewer),再將資料庫的資料輸出成報表顯示出來
最近正在寫WPF的程式,老實說這是我第一次次接觸C#及SQL SERVER,也第一次寫WPF視窗程式
雖然先前有FORM的經驗,但是我也只有點皮毛而已,所以寫這個程式時找了好多資料,跟GOOGLE每天一起抗戰
不多說
直接分享我使用的方法:
首先我們要先加入ReportViewer 所需要的API,在"方案總管"的視窗內選擇你的專案>"參考",按滑鼠右鍵,"加入參考" 給他大大的按下去,接著找以下項目:
- WindowsFormsIntegration
- Microsoft.ReportViewer.Common
- Microsoft.ReportViewer.WinForms
加入之後,打開你的View(XAML檔),參考以下程式碼:(UserControl 或 Window 皆可)
<UserControl x:Class="[專案的Namespace].[檔案的Class名稱]" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:[自訂命名1]="clr-namespace:[專案的Namespace]" xmlns:[自訂命名2]="clr-namespace:Microsoft.Reporting.WinForms;
assembly=Microsoft.ReportViewer.WinForms" Width="800" Height="600"> <UserControl.Resources> <[自訂命名1]:[資料集DataSet] x:Key="[自訂Resource命名]" /> </UserControl.Resources> <Grid> <WindowsFormsHost Width="800" Height="600"> <[自訂命名2]:ReportViewer x:Name="[自動ReportViewer命名]" /> </WindowsFormsHost> </Grid> </UserControl>
C#程式碼,請參考以下:
於建構子中(如果在XAML中有加入UserControl_Load或Window_Load的設定,也可以寫在裡面)
//設定資料來源
_dataSet = ([資料集DataSet])this.FindResource("[自訂Resource命名]"); _reportTableAdapter = new [TableAdapters].[相關TableAdapter](); _reportTableAdapter.Fill(_dataSet.[相關資料表]);
//設定報表屬性
_reportViewer = [自動ReportViewer命名] as ReportViewer; _reportViewer.LocalReport.ReportEmbeddedResource = @"[專案名稱].[RDLC檔案]";
//RDLC放在專案資料夾的根目錄;如果在子目錄,寫法是"[專案名稱].[目錄名稱].[RDLC檔案]"
_reportViewer.LocalReport.DataSources.Add(
new ReportDataSource(@"[RDLC檔案中設定的DataSetName]", _report)); _reportViewer.RefreshReport();
以上寫法即可將資料庫內的資料輸出成報表囉!
建議:在SQL SERVER上進行運算,再用程式輸出,這樣對程式來說比較好!
全站熱搜