2017-12-05

[筆記]如何在Visual Studio 2017內使用Rdlc報表


雖然Rdlc報表是很久前的產物了,但是要產生某些制式格式的檔案的時候,還是很好用!

最近公司網站要導入電子發票,所以每張發票都要有張發票圖檔副本留存,這個時候就想到這個好用的東西,但Visual Studio 2017裡面,預設把報表相關的東西都拿掉了,所以我們必須手動加回去...

首先我們必須先到「工具」->「擴充功能與更新...」裡面,搜尋兩個工具:
1. Microsoft Reporting Services Projects
2. Microsoft Rdlc Report Designer for Visual Studio


安裝好之後,我們就可以在專案裡面新增Rdlc報表檔案了!


但光是新增報表檔案還沒有用,必須還要可以處理才行!我的需求並不需要在網頁顯示報表,而只單純需要利用報表檔案來產生制式圖檔,所以在程式碼內處理就好了,可以是dll專案或是console專案即可。

所以我們必須為專案增加參考,可使用NuGet安裝由微軟維護的套件,搜尋「Microsoft.ReportingServices.ReportViewerControl.Winforms」、「Microsoft.ReportingServices.ReportViewerControl.WebForms」這兩個套件並安裝,或是直接在套件管理器主控台內輸入:
  1. Install-Package Microsoft.ReportingServices.ReportViewerControl.Winforms
  2. Install-Package Microsoft.ReportingServices.ReportViewerControl.WebForms

就可以安裝好。


接著就可以寫程式來載入Rdlc報表並匯出成圖檔囉~
可以參考底下我寫的小範例,就可以將參數傳到報表內,並匯出成PNG圖片檔了!
  1. //產生LocalReport
  2. var report = new LocalReport {
  3. EnableExternalImages = true,
  4. ReportPath = "report.rdlc"
  5. };
  6.  
  7. //設定要傳入報表的參數
  8. var paramList = new List<ReportParameter> {
  9. new ReportParameter("Paramaaa", "abcdefg"),
  10. new ReportParameter("Parambbb", "1234567")
  11. };
  12.  
  13. //將參數傳入報表內
  14. report.SetParameters(paramList);
  15.  
  16. //指定輸出格式為PNG(若不指定,則報表在Render成Image的時候,預設會是TIFF檔)
  17. string deviceInfo = "<DeviceInfo><OutputFormat>PNG</OutputFormat></DeviceInfo>";
  18.  
  19. //取得報表Render成圖片後的內容
  20. var bytes = report.Render("Image", deviceInfo,
  21. out string mimeType, out string encoding, out string fileNameExtension,
  22. out string[] streams, out Warning[] warnings);
  23.  
  24. //這行可以將報表Render成PDF檔
  25. //var bytes = report.Render("PDF", null,
  26. // out string mimeType, out string encoding, out string fileNameExtension,
  27. // out string[] streams, out Warning[] warnings);
  28.  
  29. //指定一下檔名及路徑
  30. var fileName = $"{Guid.NewGuid().ToString("N")}.{fileNameExtension}";
  31. var savePath = "";
  32.  
  33. //存檔
  34. using (FileStream fs = new FileStream(Path.Combine(savePath, fileName), FileMode.Create)) {
  35. fs.Write(bytes, 0, bytes.Length);
  36. }

要注意的是,報表在Render成檔案,不管是圖片還是PDF,預設尺寸都會是A4格式,也就是說雖然在製作Rdlc檔案時,內容並沒有很大,但匯出時還是會變成A4大小喔,沒有滿的地方就會由空白補滿,這點是要注意一下的~如果想要有其他尺寸,記得在屬性那先設定一下喔~

沒有留言:

張貼留言