ASP.NET MVC 初学笔记.3 MVC5、EF、RDLC实现报表操作
来源:互联网 发布:2016网络伤感歌曲大全 编辑:程序博客网 时间:2024/06/11 07:57
在ASP.NET的研究学习中又要用到报表,比如在OA系统里实现凭证、文件等,报表是一个必不可少的东西,但百度了一圈,发现讲得最多的还是水晶报表等第三方报表,好像微软原装的RDLC报表随着MVC的升级渐渐淡出了报表圈?本着原装的就是最好的契合度的想法,于是开始了默默的研究使用配置RDLC报表。
本次仍然用之前已建好的test实例
ASP.NET MVC 初学笔记.1 EF连接数据库的多种方法
ASP.NET MVC 初学笔记.2 一个View多个Models的对应
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语言来实现。