代码改变世界

asp.net mvc4 使用RDLC

2016-08-31 16:07  防民之口甚于防川  阅读(776)  评论(0)    收藏  举报

第一步:新建一个MVC4应用程序 

选择空模板

新增一个Controller 命名为 HomeController

 

 第二部:新建数据源

现在项目下新增一个rdlc文件。

右击rdlc文件夹新增数据源

打开rdlcdata.xsd,在空白处右击添加数据表

右击数据表,新增列

下图为新增完数据列的数据表

 

 第三步:

右击rdlc文件夹添加rdlc报表文件

之后打开rdlcreport.rdlc文件,在空白处右击添加表格

之后再弹出的窗口做如下设置

第四步

加载数据显示rdlc

项目中添加引用dll

将下段代码填写到Action Index中

            DataTable dt = new DataTable();

            dt.Columns.Add("DataColumn1");

            dt.Columns.Add("DataColumn2");

            dt.Columns.Add("DataColumn3");

            dt.Columns.Add("DataColumn4");

            DataRow dr = dt.NewRow();

            for (int i = 0; i < 100; i++)

            {

                dr["DataColumn1"] = "DataColumn1" + i;

                dr["DataColumn2"] = "DataColumn2" + i;

                dr["DataColumn3"] = "DataColumn3" + i;

                dr["DataColumn4"] = "DataColumn4" + i;

                dt.Rows.Add(dr);

                dr = dt.NewRow();

            }

 

            LocalReport localReport = new LocalReport();

            localReport.ReportPath = Server.MapPath("~/rdlc/rdlcreport.rdlc");

            ReportDataSource reportDataSource = new ReportDataSource("rdlcdata", dt);

 

            localReport.DataSources.Add(reportDataSource);

            string reportType = "PDF";

            string mimeType;

            string encoding;

            string fileNameExtension;

 

            //The DeviceInfo settings should be changed based on the reportType

            //http://msdn2.microsoft.com/en-us/library/ms155397.aspx

            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;

 

            //Render the report

            renderedBytes = localReport.Render(

                reportType,

                deviceInfo,

                out mimeType,

                out encoding,

                out fileNameExtension,

                out streams,

                out warnings);

            //Response.AddHeader("content-disposition", "attachment; filename=NorthWindCustomers." + fileNameExtension);

            return File(renderedBytes, mimeType);

 

这个方法是将rdlc以pdf文件形式输出。

第五步

运行检验效果。

搞定。