在运行时从DataGridView动态创建RDLC报表

7
我有一个名为AdvancedSearchForm的窗体,里面有一个C# Winform中的dgrData DataGridView控件和一个名为Report的按钮。当单击Report按钮时,我希望显示一个带有相同列名的ReportView控件的窗体。

带有DataGridView和Button的窗体

enter image description here

单击“Report”按钮预期输出:

enter image description here

我的DatagridView (dgrData) 控件关联了

  1. SQL
Select Id, c_Name from Country”
  1. 连接字符串
server=localhost;User Id=root;password=root;Persist Security Info=True;database=country_state
为了在运行时将数据加载到网格中,我准备了以下DataAdapter
DataAdapter dataAdapter = DataAdapter.Current;
// I am passing the SQL statement and the table name to my database which knows the ConnectionString within the LoadData function

DataTable dt0 = dataAdapter.LoadData("select Id, c_Name from `country`", "country");
if (dt0 != null) {
   dgrData.DataSource = dt0;
}

是否可以在运行时调用包含默认的reportviewer控件的子窗体,该控件显示与datagridview(dgrData)对应的列的表格报告数据?
详细期望输出:
1. 点击按钮后,目标窗体上的reportviewer应该与值来源于DataGridView的数据源相关联。因此,在用户单击运行时报告按钮之前,ReportViewer控件不知道报告中的数据。
2. 我希望解决方案不需要创建单独的RDLC文件,因为这会导致外部依赖关系,并停止当前流程并在报告文件设计器中创建一个报告文件,这可能会使用户感到不知所措。
3. 我不知道RDLC设计师和关联数据源(我愿意学习(^_^),但我不能强制我的团队接受这种学习要求),以及将数据绑定到报告。如果您的帮助包含理论,请提供工作代码示例。
4. 我知道ReportViewer已经存在了很长时间。希望未来的SO用户能更容易地找到一对一数据映射的示例解决方案,用于数据网格和ReportViewer之间的映射。
请注意:如果需要其他数据,请在评论中告诉我。为了显示当前解决方案,我必须创建一个RDLC文件,在其中必须在设计时放置连接字符串和SQL,我希望在寻找的解决方案中避免这种情况。我希望找到一种解决方案,可以通过某些模块化代码生成RDLC文件,并且可以在其他解决方案中使用,而不必为每个具有DataGrids的窗体设计它。

将 DataTable 传递给 ReportViewer - Reza Aghaei
让我尝试用C#解决方案,然后回到这个链条。 - Ganesh Kamath - 'Code Frenzy'
作为另一种选择,您可以使用 DrawToBitmap 方法打印 DataGridView 控件。 - Reza Aghaei
在运行时创建一个动态的rdlc报表并不容易。 - Reza Aghaei
@rezaAghaei,我想知道你是否可以用C#展示那个解决方案,我发现VB有点难以阅读和翻译。我还没有正式编写过那种语言的代码。 - Ganesh Kamath - 'Code Frenzy'
显示剩余8条评论
1个回答

7
作为运行时动态创建RDLC报表的选项,您可以使用运行时文本模板
在下面的示例中,我创建了一个简单的网格报表,可用于在运行时动态创建报表。您可以动态添加列到报表并设置列的标题、宽度和头部背景颜色。
在此示例中,我使用了DataGridView填充模板。但是您可以根据任何类型的控件使用此技术,甚至可以在Web表单中使用它。 示例用法-创建和显示动态报表 要创建和显示动态报表,只需向ReportForm添加一些列,然后设置数据并显示该窗体即可。
var f = new ReportForm();
f.ReportColumns = this.dataGridView1.Columns.Cast<DataGridViewColumn>()
                      .Select(x => new ReportColumn(x.DataPropertyName)
                      { Title = x.HeaderText, Width = x.Width }).ToList();
f.ReportData = this.dataGridView1.DataSource;
f.ShowDialog();

enter image description here

解决方案路径

只需将ReportColumnDynamicReport.ttReportForm添加到您的应用程序中,甚至可以在可重用库中添加一次,然后像上面的示例一样简单地使用。按照以下步骤创建动态报告模板。

报告列模型

创建一个报告列模型,其中包含标题、表达式、颜色等属性。我们将使用此模型向报告添加列。

using System;
using System.Drawing;
public class ReportColumn
{
    public ReportColumn(string name)
    {
        Name = name;
        Title = name;
        Type = typeof(System.String);
        Width = GetPixelFromInch(1);
        Expression = string.Format("=Fields!{0}.Value", name);
        HeaderBackColor = Color.LightGray;
    }
    public string Name { get; set; }
    public string Title { get; set; }
    public Type Type { get; set; }
    public int Width { get; set; }
    public float WidthInInch
    {
        get { return GetInchFromPixel(Width); }
    }
    public string Expression { get; set; }
    public Color HeaderBackColor { get; set; }
    public string HeaderBackColorInHtml
    {
        get { return ColorTranslator.ToHtml(HeaderBackColor); }
    }
    private int GetPixelFromInch(float inch)
    {
        using (var g = Graphics.FromHwnd(IntPtr.Zero))
            return (int)(g.DpiY * inch);
    }
    private float GetInchFromPixel(int pixel)
    {
        using (var g = Graphics.FromHwnd(IntPtr.Zero))
            return (float)pixel / g.DpiY;
    }
}

报告模板

将运行时模板(也称为预处理模板)添加到项目中,并将其命名为DynamicReport.tt,然后将此内容复制到文件中:

<#@ template language="C#" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ parameter name="Model" type="System.Collections.Generic.List<ReportColumn>"#>
<?xml version="1.0" encoding="utf-8"?>
<Report xmlns:rd="http://schemas.microsoft.com/SQLServer/reporting/reportdesigner" xmlns="http://schemas.microsoft.com/sqlserver/reporting/2008/01/reportdefinition">
  <DataSources>
    <DataSource Name="DataSource1">
      <ConnectionProperties>
        <DataProvider>System.Data.DataSet</DataProvider>
        <ConnectString>/* Local Connection */</ConnectString>
      </ConnectionProperties>
      <rd:DataSourceID>e9784bb0-a630-49cc-b7f9-8495aca23a6c</rd:DataSourceID>
    </DataSource>
  </DataSources>
  <DataSets>
    <DataSet Name="DataSet1">
      <Fields>
<#    foreach(ReportColumn column in Model){#>
        <Field Name="<#=column.Name#>">
          <DataField><#=column.Name#></DataField>
          <rd:TypeName><#=column.Type.Name#></rd:TypeName>
        </Field>
<#    }#>
      </Fields>
      <Query>
        <DataSourceName>DataSource1</DataSourceName>
        <CommandText>/* Local Query */</CommandText>
      </Query>
      <rd:DataSetInfo>
        <rd:DataSetName />
        <rd:TableName />
        <rd:ObjectDataSourceType />
      </rd:DataSetInfo>
    </DataSet>
  </DataSets>
  <Body>
    <ReportItems>
      <Tablix Name="Tablix1">
        <TablixBody>
          <TablixColumns>
<#    foreach(ReportColumn column in Model){#>
            <TablixColumn>
              <Width><#=column.WidthInInch#>in</Width>
            </TablixColumn>
<#    }#>
          </TablixColumns>
          <TablixRows>
            <TablixRow>
              <Height>0.25in</Height>
              <TablixCells>
<#    foreach(ReportColumn column in Model){#>
                <TablixCell>
                  <CellContents>
                    <Textbox Name="<#=column.Name#>TextBox">
                      <CanGrow>true</CanGrow>
                      <KeepTogether>true</KeepTogether>
                      <Paragraphs>
                        <Paragraph>
                          <TextRuns>
                            <TextRun>
                              <Value><#=column.Title#></Value>
                              <Style />
                            </TextRun>
                          </TextRuns>
                          <Style />
                        </Paragraph>
                      </Paragraphs>
                      <rd:DefaultName><#=column.Name#>TextBox</rd:DefaultName>
                      <Style>
                        <Border>
                          <Color>LightGrey</Color>
                          <Style>Solid</Style>
                        </Border>
                        <BackgroundColor><#=column.HeaderBackColorInHtml#></BackgroundColor>
                        <PaddingLeft>2pt</PaddingLeft>
                        <PaddingRight>2pt</PaddingRight>
                        <PaddingTop>2pt</PaddingTop>
                        <PaddingBottom>2pt</PaddingBottom>
                      </Style>
                    </Textbox>
                  </CellContents>
                </TablixCell>
<#    }#>
              </TablixCells>
            </TablixRow>
            <TablixRow>
              <Height>0.25in</Height>
              <TablixCells>
<#    foreach(ReportColumn column in Model){#>
                <TablixCell>
                  <CellContents>
                    <Textbox Name="<#=column.Name#>">
                      <CanGrow>true</CanGrow>
                      <KeepTogether>true</KeepTogether>
                      <Paragraphs>
                        <Paragraph>
                          <TextRuns>
                            <TextRun>
                              <Value><#=column.Expression#></Value>
                              <Style />
                            </TextRun>
                          </TextRuns>
                          <Style />
                        </Paragraph>
                      </Paragraphs>
                      <rd:DefaultName><#=column.Name#></rd:DefaultName>
                      <Style>
                        <Border>
                          <Color>LightGrey</Color>
                          <Style>Solid</Style>
                        </Border>
                        <PaddingLeft>2pt</PaddingLeft>
                        <PaddingRight>2pt</PaddingRight>
                        <PaddingTop>2pt</PaddingTop>
                        <PaddingBottom>2pt</PaddingBottom>
                      </Style>
                    </Textbox>
                  </CellContents>
                </TablixCell>
<#    }#>
              </TablixCells>
            </TablixRow>
          </TablixRows>
        </TablixBody>
        <TablixColumnHierarchy>
          <TablixMembers>
<#    foreach(ReportColumn column in Model){#>
            <TablixMember />
<#    }#>
          </TablixMembers>
        </TablixColumnHierarchy>
        <TablixRowHierarchy>
          <TablixMembers>
            <TablixMember>
              <KeepWithGroup>After</KeepWithGroup>
            </TablixMember>
            <TablixMember>
              <Group Name="Details" />
            </TablixMember>
          </TablixMembers>
        </TablixRowHierarchy>
        <DataSetName>DataSet1</DataSetName>
        <Top>0.15625in</Top>
        <Left>0.125in</Left>
        <Height>0.5in</Height>
        <Width>2in</Width>
        <Style>
          <Border>
            <Style>None</Style>
          </Border>
        </Style>
      </Tablix>
    </ReportItems>
    <Height>0.82292in</Height>
    <Style />
  </Body>
  <Width>6.5in</Width>
  <Page>
    <LeftMargin>1in</LeftMargin>
    <RightMargin>1in</RightMargin>
    <TopMargin>1in</TopMargin>
    <BottomMargin>1in</BottomMargin>
    <Style />
  </Page>
  <rd:ReportID>60987c40-62b1-463b-b670-f3fa81914e33</rd:ReportID>
  <rd:ReportUnitType>Inch</rd:ReportUnitType>
</Report>

报告表单

在项目中添加一个 Form,并将 ReportViewer 控件添加到该表单中,并将以下代码放入类中:

public partial class ReportForm : Form
{
    public ReportForm()
    {
        InitializeComponent();
        ReportColumns  = new List<ReportColumn>();
        this.Load+=new EventHandler(ReportForm_Load);
    }

    public List<ReportColumn> ReportColumns { get; set; }
    public Object ReportData { get; set; }

    private void ReportForm_Load(object sender, EventArgs e)
    {
        var report = new DynamicReport();
        report.Session = new Dictionary<string, object>();
        report.Session["Model"] = this.ReportColumns;
        report.Initialize();
        var rds = new Microsoft.Reporting.WinForms.ReportDataSource("DataSet1", this.ReportData);
        this.reportViewer1.LocalReport.DataSources.Clear();
        this.reportViewer1.LocalReport.DataSources.Add(rds);
        var reportContent = System.Text.Encoding.UTF8.GetBytes(report.TransformText());
        using (var stream = new System.IO.MemoryStream(reportContent))
        {
            this.reportViewer1.LocalReport.LoadReportDefinition(stream);
        }
        this.reportViewer1.RefreshReport();
    }
}

注意

您可以简单地扩展ReportColumn模型,以及DynamicReport.tt。我使用现有报告创建了模板,只是使用了一些t4代码标记使其动态。

示例

您可以克隆或下载一个工作示例:


谢谢,这似乎完全模仿了DataGrid,并暂时解决了问题。我想知道在预处理器模板中是否有灵活性,以使其以更自定义的格式显示。特别是在我们需要根据报告需求合并行和列的情况下。 - Ganesh Kamath - 'Code Frenzy'
上面显示的.tt文件似乎是XML格式的,请问您能否展示一下相同内容的HTML实现呢?... - Ganesh Kamath - 'Code Frenzy'
请您将此转换为代码,但请不要使用Lambda表达式。 - Ganesh Kamath - 'Code Frenzy'
1
在运行时创建动态报告并不容易,在实际的项目环境中,我认为我的答案只是一个起点,但它确实是一个非常优雅和有用的解决方案。如果你理解了这个想法,它将对你在许多情况下都很有用,比如你需要创建模板,例如包含客户购买产品的电子邮件模板。在我看来,这个想法非常棒! - Reza Aghaei
此外,我在这里发布的 HTML 答案是那些想要创建 HTML 输出的人的很好的起点,但大多数用户对于运行时 T4 模板没有任何概念,也不知道它是如何工作的。由于答案有点长,所以被忽略了;但实际上它非常有用。 - Reza Aghaei
显示剩余20条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接