Отчеты RDLC в приложении mvc3 - PullRequest
4 голосов
/ 23 августа 2011

Отчеты должны быть сгенерированы в моем приложении MVC3, Как я могу использовать RDLC в mvc3.Пожалуйста, кто-нибудь может дать мне примерное объяснение и рекомендации, которым нужно следовать при создании отчетов RDLC в моем приложении MVC3.

спасибо

Ответы [ 3 ]

4 голосов
/ 21 февраля 2012

Это не простая задача! Вот шесть шагов для вас.

1. Web.config

Для начала откройте ваш web.config и добавьте следующее в ваш <system.web> раздел

<httpHandlers>
<add path="Reserved.ReportViewerWebControl.axd" verb="*" type="Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
    validate="false" />
</httpHandlers>

и затем в вашем теге <compilation> добавьте следующее:

  <buildProviders>
    <add extension=".rdlc" type="Microsoft.Reporting.RdlBuildProvider, Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
  </buildProviders> 

и затем внутри вашего тега <system.webServer> добавьте это:

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

, а также добавить ссылку на Microsoft.ReportViewer.Common.dll и Microsoft.ReportViewer.WebForms.dll (версия 10.0.0.0).

2. Global.asax

Откройте ваш Global.asax.cs и в функцию RegisterRoutes () добавьте следующее:

//Reports Viewers depend on Viewstate so are hosted in class ASPX web forms, so bypassing MVC3 routing
routes.IgnoreRoute("ReportViewer/");  

Пока вы делаете это, создайте новую папку с именем «ReportViewer» в приложении asp.net.

3. Набор данных XSD

Создайте новый XSD-файл в корне папки вашего проекта (да, это должен быть корень!).

Щелкните правой кнопкой мыши по вашему проекту, нажмите «Добавить новый набор данных». Он должен быть пустым.

Щелкните правой кнопкой мыши по нему и перейдите в Add, TableAdapter ...

Выберите строку подключения к вашей базе данных. Сохраните его в конфиге приложения. Использовать существующий сохраненный процесс. Заполните набор данных с помощью запроса SELECT. Дайте набору данных значимое имя.

4. Создайте свой отчет RDLC

Создайте новый файл отчета RDLC (для этого вам понадобятся инструменты BI) и перейдите к «Добавить набор данных». Выберите новый набор данных. Создайте отчет. Запишите имя набора данных. (Например, «DataSet1», не забудьте изменить его позже на что-то более полезное.)

5. Настройте страницу ASPX

Создать новую веб-форму ASP.NET, да, веб-форму Страница с названием ShowReport.aspx. HTML должен иметь следующее:

<body>
<form id="form1" runat="server" >
    <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
    <rsweb:ReportViewer  
        ID="ReportViewer1"  
        SizeToReportContent="False" 
        Width="820px"
        Height="820px"
        runat="server"  
        ShowRefreshButton="false"
        AsyncRendering="false" 
        DocumentMapCollapsed="True" 
        PageCountMode="Actual" 
        PromptAreaCollapsed="True"></rsweb:ReportViewer>
</form>
</body>

6. Codebehind

В коде для ваших reports.aspx.cs сделайте это:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
                DataSet dataset  =  GetPopulatedDatasetFromDB()    // Populate your dataset here by calling the stored proc.

                ReportViewer1.ProcessingMode = Microsoft.Reporting.WebForms.ProcessingMode.Local;
                ReportViewer1.LocalReport.ReportPath = Server.MapPath("/Reports/MyNewReport.rdlc");
                ReportViewer1.LocalReport.DataSources.Clear();
                ReportViewer1.LocalReport.DataSources.Add(
                    new Microsoft.Reporting.WebForms.ReportDataSource("DataSet1", dataset.Tables[0]));

                ReportViewer1.LocalReport.Refresh();
        }
    }

Посетите вашу страницу:

http://localhost/MyApp/ReportViewer/ShowReport.aspx

Voila!

4 голосов
/ 02 сентября 2011

Я недавно использовал отчеты RDLC в приложении MVC3 для экспорта результатов в электронную таблицу Excel.

    private class ExcelReport 
    {
        private string encoding;
        private string[] streams;
        private Warning[] warnings; 
        private string fileNameExtension;
        private string mimeType; 
        public ExcelReport()
        {
            this.ReportDataSources = new List<ReportDataSource>();
        }
        public string ExportFileName { get; set; }
        public string MimeType
        {
            get
            {
                return mimeType;
            }
            private set
            {
                mimeType = value;
            }
        }
        public string Encoding
        {
            get
            {
                return encoding;
            }
            private set
            {
                encoding = value;
            }
        }
        public string FileNameExtension
        {
            get
            {
                return fileNameExtension;
            }
            private set
            {
                fileNameExtension = value;
            }
        }
        public string[] Streams
        {
            get
            {
                return streams;
            }
            private set
            {
                streams = value;
            }
        }
        public Warning[] Warnings
        {
            get
            {
                return warnings;
            }
            private set
            {
                warnings = value;
            }
        }
        public string ReportPath { get; set; }

        public IList<ReportDataSource> ReportDataSources { get; set; }
        public byte[] GetReport() 
        {

            LocalReport localReport = new LocalReport();
            localReport.ReportPath = this.ReportPath;

            foreach (var source in this.ReportDataSources)
            {
                localReport.DataSources.Add(source);
            }

            string reportType = "Excel";

            //The DeviceInfo settings should be changed based on the reportType             
            //http://msdn2.microsoft.com/en-us/library/ms155397.aspx             
            string deviceInfo =
                "<DeviceInfo>" +
                "  <OutputFormat>Excel</OutputFormat>" +
                "  <PageWidth>21cm</PageWidth>" +
                "  <PageHeight>29cm</PageHeight>" +
                "  <MarginTop>1cm</MarginTop>" +
                "  <MarginLeft>2cm</MarginLeft>" +
                "  <MarginRight>2cm</MarginRight>" +
                "  <MarginBottom>1cm</MarginBottom>" +
                "</DeviceInfo>";


            //Render the report             
            return localReport.Render(
                reportType,
                deviceInfo,
                out mimeType,
                out encoding,
                out fileNameExtension,
                out streams,
                out warnings
            );
        }
    }

Контроллер

    public ActionResult GetReport(string reportParameter1) 
    {
        /*Get data for your report that matches the dataset format in the report.*/
        IEnumerable<ReportData> list = new IEnumerable<ReportData> /*Your Report Data*/
                                          {
                                             new ReportData{Id = 1, Code="ABC"},
                                             new ReportData{Id = 2, Code="DEF"}

                                          };
        var excelReport = new ExcelReport
        {
            ExportFileName = "Your File Name",
            ReportPath = Server.MapPath("~/Content/Reports/YourReport.rdlc")

        };
        var ds = new ReportDataSource("Main", list); /* Main is the name of the dataset inside the report*/
        excelReport.ReportDataSources.Add(ds);

        var report = excelReport.GetReport();

        Response.AddHeader("content-disposition", string.Format("attachment; filename={0}.{1}", excelReport.ExportFileName, excelReport.FileNameExtension));
        Response.ContentType = "application/vnd.ms-excel";

        return File(report, excelReport.MimeType);
    }

Конечный результат долженбыть отчетом, экспортированным как документ Excel.

0 голосов
/ 02 сентября 2011

Вам нужно будет вручную сгенерировать отчет, как в примере выше. Возможно, вы захотите использовать pdf, чтобы пользователь мог просматривать его в браузере (если установлен acrobat) вместо того, чтобы загружать его сначала.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...