AndreaDO

导航

C# winform中RDLC报表绘制

C# winform中RDLC报表绘制

使用集成开发环境为VS2010,框架版本为.NET Framework4

以下我们以一个简单的学生报表作为例子。

public class Student
{
public string name{get;set;}
public string id{get;set;}
public string classes{get;set;}
public string home{get;set;}
public string imgPath{get;set;}
}

1.创建reportViewer

首先创建reportViewer来放置报表,选中工具栏的中reportviewer工具,然后拖入窗体中,选择在父容器中停靠
image

这次再选择新建项,创建数据集xsd,放入一个DataTable,取名为studentDataTable.
(数据集其他选择根据自己项目来),然后根据上面的Student类来添加列。
image

2.创建报表

接下来开始创建新报表,新建项中创建一个新报表,然后点击左上方新建,把上面的数据集设置为报表的数据集,名称为DataSet1
点击工具箱,拖一个表过来。点击表格右上面一个小矩形,选择对应的数据集数据进去。
点击图像,拖入表格中,选择外部中数据集属性。
image
依次设计好后,表格如下:
image
然后再返回窗体中的reportViewer中,选择为我们刚刚创建的报表,然后我们来运行此窗体,发现未显示,我们修改后台C#代码。
image

3.给报表传值和显示图像

创建学生数据

Student s = new Student();
            s.name = "张三";
            s.id = "001";
            s.home = "地球中国";
            s.classes = "计算机软件班";
            s.imgPath = @"file:\C:\Users\29749\Desktop\man1.png";

注意如果想要让报表中显示本地路径下的图片,前面需要加上file:\

创建DataSetDataTable数据集

 DataSet dataSet = new DataSet();
            DataTable table = new DataTable();
            table.Columns.Add("name", typeof(string));
            table.Columns.Add("id", typeof(string));
            table.Columns.Add("home", typeof(string));
            table.Columns.Add("classes", typeof(string));
            table.Columns.Add("imgPath", typeof(string));
            DataRow dataRow = table.NewRow();
            dataRow["name"] = s.name;
            dataRow["id"] = s.id;
            dataRow["home"] = s.home;
            dataRow["classes"] = s.classes;
            dataRow["imgPath"] = s.imgPath;
            table.Rows.Add(dataRow);
            dataSet.Tables.Add(table);

设置reportViewer属性

 //计算报表路径
            string reportPath = Application.StartupPath.Substring(0, Application.StartupPath.Substring(
              0, Application.StartupPath.LastIndexOf("\\")).LastIndexOf("\\"));
            reportPath += @"\Report1.rdlc";
            //图像显示必须设置
            this.reportViewer1.LocalReport.ReportPath = reportPath;
            this.reportViewer1.LocalReport.EnableExternalImages = true;
            reportViewer1.LocalReport.DataSources.Clear();
            //这里DataSet1必须和报表中数据集名称一样
            reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("DataSet1", dataSet.Tables[0]));
            this.reportViewer1.RefreshReport();

以上代码编写后,在运行窗体程序后效果如下:
image

4.报表参数的使用

如果需要在报表中再添加额外的数据,这些数据不来自于数据集,你需要添加参数。
在左边列表中右键添加报表参数,然后在需要的文本框中就可以设置内容为报表参数了。

在C#的后端中可以编写报表参数,代码如下:

//必须和参数名称一样
ReportParameter rp = new ReportParameter("img", imgPath);
            this.reportViewer1.LocalReport.SetParameters(rp);
ReportParameter rp2 = new ReportParameter("time", this.date);
            this.reportViewer1.LocalReport.SetParameters(rp2);

这样报表参数就传递过去了

posted on 2024-06-12 21:26  AndreaDO  阅读(1584)  评论(0)    收藏  举报