65.9K
CodeProject 正在变化。 阅读更多。
Home

Windows.Forms 报表

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.72/5 (14投票s)

2004 年 11 月 3 日

2分钟阅读

viewsIcon

68423

downloadIcon

1697

一种简洁、快速且易于从对象传递数据的方式

Sample Image - Reporting__WindowsForms.gif

引言

有时 Crystal Reports 并不易于使用,并且无法按我们想要的方式提供输出。

为了解决这个问题,我们只需要一个 HTML 模板文件和一个解析器类,该类读取此文件并调用我们类中的适当方法以传递动态数据。

使用代码

本文中发布的应用程序包含用 C# 编写的 Windows Forms 项目。它包含一种类似于 Persons 的类,该类将属性分组,如姓名、姓氏、出生日期、性别、电子邮件和国家/地区。我们想要在 HTML 报告中打印的数据包含在该类的对象中。它只是一个结构,但我认为它适用于解释解决方案。

最后一个类 HTMLReport 在其 Generate 方法中解析 HTML 模板文件,并在找到类似于“<@Data_To_Report>”的字符串时调用作为参数传递的对象的 Report(string data)。此字符串必须包含在 Report 方法的 switch 语句中作为一种情况。

例如,如果解析器在 HTML 模板中找到代码

<@FullName>

解析器将获取 <@FullName> 并将其作为参数发送到类 PersonReport() 方法,该方法包含如下代码

switch (data)
         {
            case"<@FullName>":
               return mName + " " + mLast;
            ....
            ....
            ....
        }

最后,解析器将创建一个新的 HTML 文件,其中包含在模板中找到的 html 设计以及类 Person 返回的字符串。就像这样

<h2><Somebody's name Somebody's last name</h2> 

Form1.cs 的想法只是为了说明一个 GUI,该 GUI 将数据填充到 Person 类中。按钮的单击事件包含以下代码

        //Create the object person and assign the values
         Persons newPerson = new Persons();
         newPerson.Name = txtName.Text;
         newPerson.Last = txtLast.Text;
         newPerson.Country = comboCountry.SelectedItem.ToString();
         newPerson.IsMale = radMale.Checked;
         newPerson.Email = txtEmail.Text;
         newPerson.BirthDate = Convert.ToDateTime( txtBirthDate.Text);

         //Create the object Report and assign object to report
         HTMLReport html = new HTMLReport(); 
         //Assign the template file 
         html.Template = "GeneralTemplate.htm";
         //Asign the new file name
         html.FileName = newPerson.Name; 
         //Generate the new Page and open it. It uses default browser
         System.Diagnostics.Process.Start(html.Generate(newPerson));

这种方法最大的改进之一是,每当您想要更改报告数据的格式或顺序时,只需编辑一个 HTML 页面即可。我们可以使用许多 HTML 编辑器,但我仍然更喜欢记事本。

与其说是对特定问题的解决方案,我更将其视为一个框架。这意味着您应该将本文视为一种工作方式,每当您需要以一种简洁、廉价且干净的方式从对象传递数据时都可以使用。显然,您必须重写代码以满足您的特定需求,但您可以遵循相同的模式来打印对象的数据。

历史

这只是版本 1.0。下次我将尝试说明具有复杂数据类型(如类型化数据集)的对象的示例。

© . All rights reserved.