最近项目用到rdlc报表,借此文重新温故一遍。
为了简单起见,数据库就借用微软的AdventureWorks。建立SSRS项目,制作完成rdl报表后,移植到web项目即可。
1.建立报表服务器项目。
2.在共享数据源中添加新数据源。
3.之后添加新报表,选择源数据(此报表数据源为Sales.vSalesPerson),即可生成报表。
4.添加参数。此处为报表名称参数。此时点击“预览”可以看到报表数据。下图为效果图。
5.新建web项目,将报表源文件移植到该项目下。
6.新建展示页面,生成一ReportView控件。
7.编写代码,指定ReportView的报表与数据源(虽然rdl文件中的CommandText节点下已经设置过查询语句,但当代码中指定数据时,会覆盖此节点内容。)
View Code
#region 绑定reportview数据源 /// <summary> /// 绑定reportview数据源 /// </summary> /// <param name="reportControl">reportview控件ID</param> /// <param name="path">rdlc报表路径</param> /// <param name="dataSourceName">报表数据集名称</param> /// <param name="sourceDt">报表数据源</param> /// <param name="dict">报表参数及相应的值</param> public static void BindReportData(ReportViewer reportControl, string path, string dataSourceName, DataTable sourceDt, Dictionary<string, string> dict) { reportControl.LocalReport.ReportPath = path; ReportDataSource rds = new ReportDataSource(dataSourceName, sourceDt); reportControl.LocalReport.DataSources.Clear(); reportControl.LocalReport.DataSources.Add(rds); if (dict != null) { List<ReportParameter> paralist = new List<ReportParameter>(); foreach (string key in dict.Keys) { ReportParameter rpReportName = new ReportParameter(); rpReportName.Name = key; rpReportName.Values.Add(dict[key]); paralist.Add(rpReportName); } reportControl.LocalReport.SetParameters( paralist.ToArray()); } reportControl.LocalReport.Refresh(); } #endregion
View Code
/// <summary> /// 普通报表 /// </summary> public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { rptvContainer_ReportRefresh(null, null); } } private DataTable GetData() { DataTable dt = new DataTable(); string text = "select * from Sales.vSalesPerson"; dt = SqlHelper.ExecuteDataset(BaseCommon.ConnectionString, CommandType.Text, text).Tables[0]; return dt; } protected void rptvContainer_ReportRefresh(object sender, System.ComponentModel.CancelEventArgs e) { string path = Server.MapPath("~/Rdlc/Report01.rdl"); Dictionary<string, string> dict = new Dictionary<string, string>(); dict.Add("Title", "普通报表"); BaseCommon.BindReportData(rptvContainer, path, "DataSet1", GetData(), dict); } }
(若后续文章中用到上述代码,文中不在显示)
注意:rdlc报表参数是一参数对应多值,后续文章会概括。
至此,此报表完成。