1. 程式人生 > >ASP.NET MVC 初學筆記.3 MVC5、EF、RDLC實現報表操作

ASP.NET MVC 初學筆記.3 MVC5、EF、RDLC實現報表操作

在ASP.NET的研究學習中又要用到報表,比如在OA系統裡實現憑證、檔案等,報表是一個必不可少的東西,但百度了一圈,發現講得最多的還是水晶報表等第三方報表,好像微軟原裝的RDLC報表隨著MVC的升級漸漸淡出了報表圈?本著原裝的就是最好的契合度的想法,於是開始了默默的研究使用配置RDLC報表。

本次仍然用之前已建好的test例項

來操作

1、首先VS2013版本(未證實)以上的RDLC都被放在了安裝檔案的Microsoft SQL Server Data Tools裡了,如果發現在新增—Reporting裡沒有選項或者就沒有Reporting就說明你必須重新執行安裝包然後勾選Microsoft SQL Server Data Tools 來安裝功能。

2、新增引用

 

3、根目錄下建Report資料夾,右鍵新增新建項:



4、在報表設計頁面的最左邊選擇資料集右鍵新增資料集,此處資料集的作用只是給報表提供繫結的欄位,資料集生成後可以直接刪除。

點選新建


選擇之前建好的EF的資料實體


此處可以不勾選,因為我們最終使用通過EF來繫結資料,因此此資料集不需要連線


選擇自己要用的表,此處選一張表也就可以了,如果還需要在此報表提現多個數據庫內容,需要再按照整個流程再新增一次


注意[名稱]後面會用到


在報表的設計頁面插入表然後把需要繫結的欄位拖入表中就完成了。


5、在Controller資料夾下新建ReportController.cs

using Microsoft.Reporting.WebForms;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.Entity;
using System.Web.Mvc;
using test.Models;

namespace test.Controllers
{
    public class ReportController:Controller
    {
        public ActionResult Index()
        {
            LocalReport localReport = new LocalReport();
            localReport.ReportPath = Server.MapPath("~/Report/TestReport.rdlc");
            DBcontest db = new DBcontest();//
            var T2 = db.Testtable2.ToList();//這裡可以使用EF的各種查詢方法
            ReportDataSource rds = new ReportDataSource("Tb2", T2);//此處"Tb2"就是TestReport報表裡資料集的名稱,一定要對應起來才可以對報表裡的正常繫結賦值
            localReport.DataSources.Add(rds);
            string reportType = "PDF";
            string mimeType;
            string encoding;
            string fileNameExtension;
            string deviceInfo =
            "<DeviceInfo>" +
            "  <OutputFormat>PDF</OutputFormat>" +
            "  <PageWidth>8.5in</PageWidth>" +
            "  <PageHeight>11in</PageHeight>" +
            "  <MarginTop>0.5in</MarginTop>" +
            "  <MarginLeft>1in</MarginLeft>" +
            "  <MarginRight>1in</MarginRight>" +
            "  <MarginBottom>0.5in</MarginBottom>" +
            "</DeviceInfo>";
            Warning[] warnings;
            string[] streams;
            byte[] renderedBytes;
            renderedBytes = localReport.Render(
                reportType,
                deviceInfo,
                out mimeType,
                out encoding,
                out fileNameExtension,
                out streams,
                out warnings);
            return File(renderedBytes, mimeType);
        }
    }
}

6、新建View—Report—Index.cshtml

7、測試

得到了一個PDF形式的報表,至於其他形式的報表,可以在Controller裡設定。


8.

實際上,RDLC報表並非相容MVC的VIEW模式,其實RDLC在WebForm裡的支援更好,操作也更簡單,可以換一種思路,只需要做好設定在MVC裡也允許呼叫ASPX檔案,然後RDLC的控制元件通過WebForm來實現操作,再將WebForm放入View裡就也實現了MVC對RDLC報表的操作。

另外,MVC的View模式展示報表應該是可以直接用Html語言來實現。