rdlc报表生成,动态生成OdysseyDLC报表

上个月,做了凯雷德DLC报表,首即使三块功效:

rdlc报表生成,动态生成OdysseyDLC报表。汉兰达DLC报表之动态变化报表,rdlc报表生成

上月,做了猎豹CS6DLC报表,首即使3块成效:

一、从DataGrid提取(包涵新型的增加和删除改)的数量,自动生成对应的OdysseyDLC报表文件(以流的款型驻存在内部存款和储蓄器中),用ReportViewer类来展现、打字与印刷、排版、预览、分页

1-一、提供二个领到率性控件数据的通用接口,然后拼接成DataTable那种网状的格子。DataGrid里修改、扩张、删除等数据变动,立时联合立异到报表

二、给1个简短的福睿斯DLC模板,提供表头的书体格式和表内部数据等体制相关的音信,然后再用DataGrid里提取的数码,生成DataTable后别的必需音信,填充到报表里,

自行调治报表格式

叁、做了贰个TreeView,很简单;依照报表文件名称,切换左侧TreeView的Item,就加载不一致的表格,突显数据。用了几许反光的文化

 

 

第壹步:依照 Report Definition Language (逍客DL) 生成对应的类和命名空间。

1、去

下载ReportDefinition2010.xsd。

专注:ReportDefinition和Visual
Studio公布的有个时辰差,官英特网有ReportDefinition2006版和ReportDefinition2008版。ReportDefinition2005版,VS二零一零及之后才支撑;

ReportDefinition2010版,VS20十及事后援助。2010版,要VS2013从此才支撑。小编的是VS20十,用ReportDefinition二零一零版就好。

 

二、找XML Schema Definition Tool
(Xsd.exe),Windows操作系统会自带(微软会自带多数功用庞大的exe,假如开源就好了)。For
more detail,please refer to:

官方网址有详尽的下令使用表达

 Below is my CMD in administator mode:

C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\x64>xsd

/c /n:RDLC  

/out:C:\Users\admin\Desktop\RDLCReportResearch

C:\Users\admin\Desktop\RDLCReportResearch\ReportDefinition.xsd

 完了,生成的是那般个样板(ReportDefinition2007的退换出来有九千行左右,ReportDefinition2010的及其后有一千0多行,贴1部分,样子参照下边代码)

美高梅开户网址 1using
System.Xml.Serialization; /// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute(“xsd”,
“2.0.50727.3038”)] [System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute(“code”)]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true,
Namespace=”]
[System.Xml.Serialization.XmlRootAttribute(Namespace=””,
IsNullable=false)] public partial class Report { private object[]
itemsField; private ItemsChoiceType80[] itemsElementNameField; private
System.Xml.XmlAttribute[] anyAttrField; /// <remarks/>
[System.Xml.Serialization.XmlAnyElementAttribute()]
[System.Xml.Serialization.XmlElementAttribute(“Author”,
typeof(string))]
[System.Xml.Serialization.XmlElementAttribute(“AutoRefresh”,
typeof(uint))] [System.Xml.Serialization.XmlElementAttribute(“Body”,
typeof(BodyType))]
[System.Xml.Serialization.XmlElementAttribute(“Classes”,
typeof(ClassesType))]
[System.Xml.Serialization.XmlElementAttribute(“Code”, typeof(string))]
[System.Xml.Serialization.XmlElementAttribute(“CodeModules”,
typeof(CodeModulesType))]
[System.Xml.Serialization.XmlElementAttribute(“ConsumeContainerWhitespace”,
typeof(bool))] ReportDefinition.cs

 

第二步:创建RDLCGenerator类和TablixRDLCGenerator类

一、依照下载的Report Definition
Language(昂CoraDL)和四个创办的大概的CR-VDLC文件,知道SportageDLC文件中央要有哪几部分组成;然后层层嵌套创立就出去了,很简单。

二-一、Tablix是主要数据区,GotReportViewer上边的例子,DynamicMatrix和DynamicTable是基于RAV4DL2005来做的,奥迪Q7DL二零零六之后,正是二个Tablix:

2-二、Tablix的要害数据区域: TablixHierarchyType
CreateTablixColumnHierarchy()和TablixHierarchyType
CreateTablixRowHierarchy()

二-三、对于HeaderRow和DataRow关键就在下边包车型客车不等。

美高梅开户网址 21 private
LocIDStringWithDataTypeAttribute CreateTablixTextRunValue(bool
isHeaderCell, string name) 2 { 3 LocIDStringWithDataTypeAttribute v =
new LocIDStringWithDataTypeAttribute(); 4 v.Value = isHeaderCell ? name
: “=Fields!” + name + “.Value”; 5 v.DataType =
StringWithDataTypeAttributeDataType.String; 6 return v; 7 } CreateTablixTextRunValue

 2-四、DataSet的名字自然要和ReportDataSource里的名字完全相配

 

CR-VdlcGenerator的Read和Write方法比较关键。

美高梅开户网址 3 /// table

  • matrix = tablix /// Microsoft 用多少个tablix来扶助Table(表),
    Matrix(矩阵) and List(列表)这两种报表项 ///
    整合了table和matrix的职能 View
    Code
    美高梅开户网址 4 #region
    Properties // DataGrid 的DataGridColumn的Header private
    List<string> headerNames = new List<string>(); public
    List<string> HeaderNames { get { return headerNames; } } //
    对应DataGrid Binding的Path private List<string> 田野同志Names = new
    List<string>(); public List<string> FieldNames { get {
    return 田野(field)Names; } } // 对应DataGrid
    Column的ActualWdith(因为其实的窗口宽度会再次计算) private
    List<double> widths = new List<double>(); public
    List<double> Widths { get { return widths; } } //
    倘使没有立异过页面设置,用ReportViewer的暗中同意页面设置;不然用新型的页面设置
    public PageSettings PageSettings { get; set; } public string Headline {
    get; set; } public string DataSourceName { get; set; } public string
    DataSetName { get; set; } #endregion #region Methods //
    1层套1层,把xml构造出来 private Report CreateReport() { Report report
    = new Report(); report.Items = new object[] { CreateDataSources(),
    CreateDataSets(), CreateBody(), CalcReportWidth(), CreatePage(), };
    report.ItemsElementName = new ItemsChoiceType80[] {
    ItemsChoiceType80.DataSources, ItemsChoiceType80.DataSets,
    ItemsChoiceType80.Body, ItemsChoiceType80.Width, ItemsChoiceType80.Page,
    }; return report; } private DataSourcesType CreateDataSources() {
    DataSourcesType dataSources = new DataSourcesType();
    dataSources.DataSource = new DataSourceType[] { CreateDataSource() };
    return dataSources; } private DataSourceType CreateDataSource() {
    DataSourceType dataSource = new DataSourceType(); dataSource.Name =
    String.IsNullOrEmpty(DataSetName) ? “TBReport” : DataSetName;
    dataSource.Items = new object[] {
    CreateDataSourceConnectionProperties() }; return dataSource; } private
    ConnectionPropertiesType CreateDataSourceConnectionProperties() {
    ConnectionPropertiesType connectionProperties = new
    ConnectionPropertiesType(); connectionProperties.Items = new object[]
    { “System.Data.DataSet”, “/* Local Connection */”, };
    connectionProperties.ItemsElementName = new ItemsChoiceType[] {
    ItemsChoiceType.DataProvider, ItemsChoiceType.ConnectString, }; return
    connectionProperties; } private DataSetsType CreateDataSets() {
    DataSetsType dataSets = new DataSetsType(); dataSets.DataSet = new
    DataSetType[] { CreateDataSet() }; return dataSets; } //
    Query目前就绝不了 private DataSetType CreateDataSet() { DataSetType
    dataSet = new DataSetType(); // DataSetName写死就好 dataSet.Name =
    “CustomerDataSet”; dataSet.Items = new object[] {
    CreateDataSetFields(), CreateDataSetQuery(), }; return dataSet; }
    private FieldsType CreateDataSetFields() { FieldsType fields = new
    FieldsType(); // DataSet的具体field由DataGrid的Bingding的Path值决定 if
    ((fieldNames != null) && (fieldNames.Count > 0)) { fields.Field = new
    FieldType[fieldNames.Count]; for (int index = 0; index <
    fieldNames.Count; index++) fields.Field[index] =
    CreateDataSetField(fieldNames[index]); } return fields; } private
    FieldType CreateDataSetField(string fieldName) { FieldType field = new
    FieldType(); field.Name = fieldName; field.Items = new object[] {
    fieldName, // CreateDataSetFieldValue(), }; return field; } //
    暂时DataType全部用String private StringWithDataTypeAttribute
    CreateDataSetFieldValue() { StringWithDataTypeAttribute value = new
    StringWithDataTypeAttribute(); value.DataType =
    StringWithDataTypeAttributeDataType.String; return value; } private
    QueryType CreateDataSetQuery() { QueryType query = new QueryType();
    query.Items = new object[] { “TBReport”, “/* Local Query */”, };
    query.ItemsElementName = new ItemsChoiceType1[] {
    ItemsChoiceType1.DataSourceName, ItemsChoiceType1.CommandText, }; return
    query; } private BodyType CreateBody() { BodyType body = new BodyType();
    body.Items = new object[] { “4.8in”, // Height CreateReportItems(), //
    ReportItems CreateBodyStyle(), }; return body; } private ReportItemsType
    CreateReportItems() { ReportItemsType reportItems = new
    ReportItemsType(); // 那是最首要数据区域 TablixRubicondlcGenerator tablixGen =
    new Tablix昂科威dlcGenerator(); tablixGen.ResetHeaderNames(HeaderNames);
    tablixGen.ResetFieldNames(菲尔德Names); List<string>
    tablixColumnWidths;
    DataGridHelper.CalcTablixColumnWidth(CalcReportWidth(), Widths, out
    tablixColumnWidths); tablixGen.ResetWidths(tablixColumnWidths);
    reportItems.Items = new object[] { CreateReportHeadlineTextbox(),
    tablixGen.CreateTablix() }; return reportItems; } // 创设标题 private
    TextboxType CreateReportHeadlineTextbox() { TextboxType headlineTextbox
    = new TextboxType(); headlineTextbox.Name = “headlineTextbox”; string
    left = (PageSettings == null) ? “二cm” :
    ((double)PageSettings.Margins.Left / 十0.0).ToString() + “in”; string
    width = (PageSettings == null) ? “一七cm” :
    ((double)(PageSettings.PaperSize.Width – PageSettings.Margins.Left –
    PageSettings.Margins.Right) / 十0.0).ToString() + “in”;
    headlineTextbox.Items = new object[] { true, true,
    CreateHeadlineTextboxParagraphs(), left, “0.5cm”, “1.0cm”, width,
    CreateHeadlineTextboxStyle() }; headlineTextbox.ItemsElementName = new
    ItemsChoiceType14[] { ItemsChoiceType14.CanGrow,
    ItemsChoiceType14.KeepTogether, ItemsChoiceType14.Paragraphs,
    ItemsChoiceType14.Left, ItemsChoiceType14.Top, ItemsChoiceType14.Height,
    ItemsChoiceType14.Width, ItemsChoiceType14.Style }; return
    headlineTextbox; } private ParagraphsType
    CreateHeadlineTextboxParagraphs() { ParagraphsType headlineParagraphs =
    new ParagraphsType(); headlineParagraphs.Paragraph = new
    ParagraphType[] {CreateHeadlineTextboxParagraph()}; return
    headlineParagraphs; } private ParagraphType
    CreateHeadlineTextboxParagraph() { ParagraphType pt = new
    ParagraphType(); pt.Items = new object[] { CreateHeadlineTextRuns(),
    CreateHeadlineParagraphStyle() }; pt.ItemsElementName = new
    ItemsChoiceType12[] { ItemsChoiceType12.TextRuns,
    ItemsChoiceType12.Style, }; return pt; } private TextRunsType
    CreateHeadlineTextRuns() { TextRunsType trt = new TextRunsType();
    trt.TextRun = new TextRunType[] { CreateHeadlineTextRun() }; return
    trt; } private TextRunType CreateHeadlineTextRun() { TextRunType trt =
    new TextRunType(); trt.Items = new object[] {
    CreateHeadLineTextRunValue(), CreateHeadlineTextRunStyle() };
    trt.ItemsElementName = new ItemsChoiceType11[] {
    ItemsChoiceType11.Value, ItemsChoiceType11.Style }; return trt; }
    private LocIDStringWithDataTypeAttribute CreateHeadLineTextRunValue() {
    LocIDStringWithDataTypeAttribute value = new
    LocIDStringWithDataTypeAttribute(); value.Value = (Headline == null) ?
    “标题” : Headline; value.DataType =
    StringWithDataTypeAttributeDataType.String; return value; } private
    StyleType CreateHeadlineTextRunStyle() { StyleType st = new StyleType();
    st.Items = new object[] { “宋体”, “14pt”, “Bold”, };
    st.ItemsElementName = new ItemsChoiceType4[] {
    ItemsChoiceType4.FontFamily, ItemsChoiceType4.FontSize,
    ItemsChoiceType4.FontWeight }; return st; } private StyleType
    CreateHeadlineParagraphStyle() { StyleType st = new StyleType();
    st.Items = new object[] { “Center” }; st.ItemsElementName = new
    ItemsChoiceType4[] { ItemsChoiceType4.TextAlign }; return st; }
    private StyleType CreateHeadlineTextboxStyle() { StyleType headlineStyle
    = new StyleType(); headlineStyle.Items = new object[] {
    CreateHeadlineTextboxBorder(), “2pt”, “2pt”, “2pt”, “2pt” };
    headlineStyle.ItemsElementName = new ItemsChoiceType4[] {
    ItemsChoiceType4.Border, ItemsChoiceType4.PaddingLeft,
    ItemsChoiceType4.PaddingRight, ItemsChoiceType4.PaddingTop,
    ItemsChoiceType4.PaddingBottom }; return headlineStyle; } private
    BorderType CreateHeadlineTextboxBorder() { BorderType
    headlineTextboxBorder = new BorderType(); headlineTextboxBorder.Items =
    new object[] { “None” }; headlineTextboxBorder.ItemsElementName = new
    ItemsChoiceType2[] { ItemsChoiceType二.Style }; return
    headlineTextboxBorder; } private StyleType CreateBodyStyle() { return
    new StyleType(); } /// <summary> ///
    设置页面基本属性—页眉、页脚、页宽、页高、左侧距、左侧距等 ///
    </summary> private PageType CreatePage() { PageType page = new
    PageType(); // 依照微软官方文书档案,PaperSize.Height, 帕佩rSize.Width and
    Margins的Left, Right, Top, Bottom are in hundredths of an inch. string
    pageHeight = (PageSettings == null) ? “2玖.7cm” :
    ((double)PageSettings.PaperSize.Height / 100.0).ToString() + “in”;
    string pageWidth = (PageSettings == null) ? “二一cm” :
    ((double)PageSettings.PaperSize.Width / 100.0).ToString() + “in”; string
    leftMargin = (PageSettings == null) ? “二cm” :
    ((double)PageSettings.Margins.Left / 十0.0).ToString() + “in”; string
    rightMargin = (PageSettings == null) ? “2cm” :
    ((double)PageSettings.Margins.Right / 十0.0).ToString() + “in”; string
    topMargin = (PageSettings == null) ? “2cm” :
    ((double)PageSettings.Margins.Top / 100.0).ToString() + “in”; string
    bottomMargin = (PageSettings == null) ? “二cm” :
    ((double)PageSettings.Margins.Bottom / 拾0.0).ToString() + “in”; //
    TODO: // 页眉、页脚(后边再做) page.Items = new object[] {
    //创立Header不能够为空 // CreatePageHeader(), pageHeight, pageWidth,
    leftMargin, rightMargin, topMargin, bottomMargin, “0.一三cm”, };
    page.ItemsElementName = new ItemsChoiceType77[] { //
    ItemsChoiceType77.PageHeader, ItemsChoiceType7七.PageHeight,
    ItemsChoiceType77.PageWidth, ItemsChoiceType77.LeftMargin,
    ItemsChoiceType77.RightMargin, ItemsChoiceType7七.TopMargin,
    ItemsChoiceType7七.BottomMargin, ItemsChoiceType7七.ColumnSpacing };
    return page; } /// <summary> ///
    PageHeader和PageFooter也只是TextRun里Value的数码不等同 ///
    </summary> /// <returns></returns> private
    PageSectionType CreatePageHeader() { return new PageSectionType(); }
    private PageSectionType CreatePageFooter() { return new
    PageSectionType(); } /// <summary> /// 把Report系列化为流 ///
    </summary> /// <param
    name=”stream”>依据Report系列化好的流</param> public void
    Write(Stream stream) { Write(stream, CreateReport()); } public void
    Write(Stream stream, Report report) { new
    XmlSerializer(typeof(Report)).Serialize(stream, report); } public Report
    Read(Stream stream) { return (Report)new
    XmlSerializer(typeof(Report)).Deserialize(stream); } /// <summary>
    /// 把和DataGrid对应的rdlc模板文件反种类化为Report /// </summary>
    /// <param
    name=”rdlcModelFilePath”>和DataGrid对应的rdlc模板文件</param>
    /// <returns>反类别化之后的Report</returns> public Report
    Read(string rdlcModelFilePath) { using (var stream = new
    FileStream(rdlcModelFilePath, FileMode.Open)) { return Read(stream); } }
    public void Write(string rdlcModelFilePath) { using (var stream = new
    FileStream(rdlcModelFilePath, FileMode.OpenOrCreate)) {
    stream.SetLength(0); Write(stream); } } /// <summary> ///
    计算Report的幅度,页宽 – 左边距 – 右侧距 /// </summary> ///
    <returns></returns> public string CalcReportWidth() { string
    reportWidth = String.Empty; const double size = 拾0.0; reportWidth =
    (PageSettings == null) ? “6.五in” :
    ((double)(PageSettings.PaperSize.Width – PageSettings.Margins.Left –
    PageSettings.Margins.Right) / size).ToString() + “in”; return
    reportWidth; } 福特ExplorerdlcGenerator.cs
    美高梅开户网址 5 public
    class TablixRdlcGenerator { #region Properties // DataGrid
    的DataGridColumn的Header private List<string> headerNames = new
    List<string>(); public List<string> HeaderNames { get {
    return headerNames; } } // 对应DataGrid Binding的Path private
    List<string> fieldNames = new List<string>(); public
    List<string> FieldNames { get { return fieldNames; } } public
    string DataSetName { get; set; } // 对应DataGrid Column的ActualWidth
    private List<string> widths = new List<string>(); public
    List<string> Widths { get { return widths; } } #endregion
    #region Methods private void ResetValues(List<string> p,
    List<string> v) { p.Clear(); if (v != null) { p.AddRange(v); } }
    public void ResetHeaderNames(List<string> hns) {
    ResetValues(HeaderNames, hns); } public void
    ResetFieldNames(List<string> fns) { ResetValues(FieldNames, fns);
    } public void ResetWidths(List<string> widths) {
    ResetValues(Widths, widths); } /// <summary> ///
    矩阵和Table对应的Tablix稍微有个别不1致,如对于矩阵,TablixBody里的表头和数目项
    ///
    一些值会拆分到TablixColumnHierarchy和TablixRowHierarchy里TablixMember–TablixHeader–CellContents–Textbox
    /// 对于DataGrid大家用最简便的Table就好 /// </summary> ///
    <returns></returns> public TablixType CreateTablix() {
    TablixType tablix = new TablixType(); tablix.Name = “dataGridTablix0”;
    tablix.Items = new object[] { // 成立TablixCorner不可能成立个空的 //
    CreateTablixCorner(), CreateTablixBody(), CreateTablixColumnHierarchy(),
    CreateTablixRowHierarchy(), true, true, CreateDataSetName(), // Top,
    Left, Height, Width可实际调治 // Top, Left —>
    Location(距离左上角);Height, Width —> Size //
    (Tablix的高低,那么些Width不管用,具体是由逐壹TablixColumn的Width之和调节)
    “一.八cm”, “二cm”, “二cm”, “一七cm”, CreateTablixStyle(), };
    tablix.ItemsElementName = new ItemsChoiceType7三[] { //
    ItemsChoiceType73.TablixCorner, ItemsChoiceType7三.TablixBody,
    ItemsChoiceType7三.TablixColumnHierarchy,
    ItemsChoiceType7三.TablixRowHierarchy,
    ItemsChoiceType7三.RepeatColumnHeaders,
    ItemsChoiceType7三.RepeatRowHeaders, ItemsChoiceType7三.DataSetName,
    ItemsChoiceType7叁.Top, ItemsChoiceType7叁.Left, ItemsChoiceType73.Height,
    ItemsChoiceType7三.Width, ItemsChoiceType7三.Style }; return tablix; } ///
    <summary> /// non-essential element, so make it emtpy temprorily
    /// 看样子是表头行,纵向合并的单元格(如纵向两行统1为一行)等连锁的 ///
    </summary> /// <returns></returns> private
    TablixCornerType CreateTablixCorner() { return new TablixCornerType(); }
    private TablixBodyType CreateTablixBody() { TablixBodyType tablixBody =
    new TablixBodyType(); tablixBody.Items = new object[] {
    CreateTablixColumns(), CreateTablixRows(), }; return tablixBody; }
    private void EnumHeaderNames(Action<int> act) { for (int i = 0; i
    < HeaderNames.Count; i++) { act(i); } } private TablixColumnsType
    CreateTablixColumns() { TablixColumnsType tablixColumns = new
    TablixColumnsType(); //
    根据DataGridColumns的数额来控制创设几列,并且每列要把实际的幅度传进去
    tablixColumns.Items = new object[headerNames.Count]; EnumHeaderNames(p
    => { tablixColumns.Items[p] = CreateTablixColumn(p); }); return
    tablixColumns; } private TablixColumnType CreateTablixColumn(int index)
    { // Width of
    column,应该依照DataGridColumn.Width来具体设定,一时半刻给个固定值 return new
    TablixColumnType() { Items = new object[] { Widths[index] } }; } ///
    <summary> /// 对于DataGrid只应有两行,1行是Header,一行是数量 ///
    假设有求 /// </summary> ///
    <returns>TablixRowsType</returns> private TablixRowsType
    CreateTablixRows() { TablixRowsType tablixRows = new TablixRowsType();
    tablixRows.Items = new object[] { CreateTablixRowHeader(),
    CreateTablixRowData(), }; return tablixRows; } private TablixRowType
    CreateTablixRowType(bool isHeader) { TablixRowType trt = new
    TablixRowType(); trt.Items = new object[] { “0.2362二in”, // Default
    height CreateTablixCells(isHeader), //
    Header的Cells的源委和Data的Cells的源委应当例外 }; return trt; } ///
    <summary> /// Tablix Header /// </summary> ///
    <returns></returns> private TablixRowType
    CreateTablixRowHeader() { return CreateTablixRowType(true); } private
    TablixRowType CreateTablixRowData() { return CreateTablixRowType(false);
    } private TablixCellsType CreateTablixCells(bool isHeaerCell) {
    TablixCellsType tablixCells = new TablixCellsType(); //
    依据DataGridColumns的数额来决定创办几个Cell,
    Header应传DataGridColumn.Header数据 tablixCells.Items = new
    object[HeaderNames.Count]; EnumHeaderNames(p => {
    tablixCells.Items[p] = CreateTablixCell(isHeaerCell, p); }); return
    tablixCells; } private TablixCellType CreateTablixCell(bool
    isHeaderCell, int index) { TablixCellType tablixCell = new
    TablixCellType(); // 基本的比如”CellContents”就够了 tablixCell.Items =
    new object[] { CreateCellContentes(isHeaderCell, index) }; return
    tablixCell; } private CellContentsType CreateCellContentes(bool
    isheaderCell, int index) { CellContentsType cellContents = new
    CellContentsType(); //
    对于DataGrid调换的rdlc,常常是贰个Textbox。具体可以是Chart、Image、Line、Rectangle、Subreport等等
    cellContents.Items = new object[] {
    CreateTablixCellTextbox(isheaderCell, index) };
    cellContents.ItemsElementName = new ItemsChoiceType71[] {
    ItemsChoiceType7一.Textbox }; return cellContents; } private TextboxType
    CreateTablixCellTextbox(bool isHeaderCell, int index) { TextboxType
    tablixCellTextbox = new TextboxType(); //
    对于Header的Textbox能够复杂一点,多些字体、背景颜色等字段的定义 //
    Data的轻松点//isHeaderCell ? headerNames[index] :
    tablixCellTextbox.Name = isHeaderCell ? “TB” + fieldNames[index] :
    fieldNames[index]; tablixCellTextbox.Items = new object[] { true,
    true, CreateTablixCellTextboxParagraphs(isHeaderCell, isHeaderCell ?
    headerNames[index] : fieldNames[index]),
    CreateTablixCellTextboxStyle(), }; tablixCellTextbox.ItemsElementName =
    new ItemsChoiceType14[] { ItemsChoiceType14.CanGrow,
    ItemsChoiceType14.KeepTogether, ItemsChoiceType14.Paragraphs,
    ItemsChoiceType14.Style, }; return tablixCellTextbox; } private
    ParagraphsType CreateTablixCellTextboxParagraphs(bool isHeaderCell,
    string name) { ParagraphsType pt = new ParagraphsType(); pt.Paragraph =
    new ParagraphType[] { CreateTablixCellTextboxParagraph(isHeaderCell,
    name) }; return pt; } private ParagraphType
    CreateTablixCellTextboxParagraph(bool isHeaderCell, string name) {
    ParagraphType pt = new ParagraphType(); pt.Items = new object[] {
    CreateTablixCellTextboxParagraphTextRuns(isHeaderCell, name),
    CreateTablixCellTextboxParagraphStyle(isHeaderCell), };
    pt.ItemsElementName = new ItemsChoiceType12[] {
    ItemsChoiceType12.TextRuns, ItemsChoiceType12.Style, }; return pt; }
    private TextRunsType CreateTablixCellTextboxParagraphTextRuns(bool
    isHeaderCell, string name) { TextRunsType trt = new TextRunsType();
    trt.TextRun = new TextRunType[] {
    CreateTablixCellTextboxParagraphTextRun(isHeaderCell, name) }; return
    trt; } private TextRunType CreateTablixCellTextboxParagraphTextRun(bool
    isHeaderCell, string name) { TextRunType trt = new TextRunType();
    trt.Items = new object[] { CreateTablixTextRunValue(isHeaderCell,
    name), CreateTablixTextRunStyle(isHeaderCell), }; trt.ItemsElementName =
    new ItemsChoiceType11[] { ItemsChoiceType1一.Value,
    ItemsChoiceType1一.Style, }; return trt; } //
    数据项和Header的第2不等同就在那一个了 private
    LocIDStringWithDataTypeAttribute CreateTablixTextRunValue(bool
    isHeaderCell, string name) { LocIDStringWithDataTypeAttribute v = new
    LocIDStringWithDataTypeAttribute(); v.Value = isHeaderCell ? name :
    “=菲尔德s!” + name + “.Value”; v.DataType =
    StringWithDataTypeAttributeDataType.String; return v; } private
    StyleType CreateTablixTextRunStyle(bool isHeaderCell) { StyleType st =
    new StyleType(); string fontSize = isHeaderCell ? “11pt” : “10pt”;
    string FontWeight = isHeaderCell ? “Bold” : “Default”; st.Items = new
    object[] { “宋体”, fontSize, FontWeight, }; st.ItemsElementName = new
    ItemsChoiceType4[] { ItemsChoiceType4.FontFamily,
    ItemsChoiceType4.FontSize, ItemsChoiceType四.FontWeight, }; return st; }
    //
    目前设为表头行“居中对齐”,数据行“靠左对齐”;前面可实际定制表头行和数据行的对齐情势private StyleType CreateTablixCellTextboxParagraphStyle(bool
    isHeaderCell) { StyleType st = new StyleType(); st.Items = new
    object[] { isHeaderCell ? “Center” : “Left” }; st.ItemsElementName =
    new ItemsChoiceType4[] { ItemsChoiceType4.TextAlign }; return st; } //
    ***************************** //
    Header的Color和Style能够和数目不相同,上边是暗中认可的Sytle,可自定义
    //****************************** private
    StyleType CreateTablixCellTextboxStyle() { StyleType st = new
    StyleType(); st.Items = new object[] {
    CreateTablixCellTextboxBorder(), “2pt”, “2pt”, “2pt”, “2pt”, };
    st.ItemsElementName = new ItemsChoiceType4[] {
    ItemsChoiceType四.Border, // ItemsChoiceType四.BackgroundColor,
    暗中同意数据尚未BackgroundColor ItemsChoiceType4.PaddingLeft,
    ItemsChoiceType4.PaddingRight, ItemsChoiceType4.PaddingTop,
    ItemsChoiceType肆.PaddingBottom, }; return st; } private BorderType
    CreateTablixCellTextboxBorder() { BorderType bt = new BorderType();
    bt.Items = new object[] { “Black”, “Solid”, “1pt” };
    bt.ItemsElementName = new ItemsChoiceType2[] { ItemsChoiceType二.Color,
    ItemsChoiceType2.Style, ItemsChoiceType贰.Width }; return bt; } ///
    <summary> ///
    按最简便的来,DataGrid对应的应当是有多少个column创立多少个TablixMember ///
    </summary> private TablixHierarchyType
    CreateTablixColumnHierarchy() { return new TablixHierarchyType() { Items
    = new object[] { CreateTablixColumnMembers() } }; } private
    TablixMembersType CreateTablixColumnMembers() { TablixMembersType tmts =
    new TablixMembersType(); tmts.TablixMember = new
    TablixMemberType[HeaderNames.Count]; EnumHeaderNames(p => {
    tmts.TablixMember[p] = CreateTablixColumnMember(); }); return tmts; }
    // DataGrid的Column对应的TablixMember创建三个空的就行 private
    TablixMemberType CreateTablixColumnMember() { return new
    TablixMemberType(); } //
    DataGrid按最轻易易行的暗中同意的来,即成立3个TablixMember就可以 private
    TablixHierarchyType CreateTablixRowHierarchy() { return new
    TablixHierarchyType() { Items = new object[] {
    CreateTablixRowMembers() } }; } private TablixMembersType
    CreateTablixRowMembers() { TablixMembersType tablixMembers = new
    TablixMembersType(); tablixMembers.TablixMember = new
    TablixMemberType[] { CreateTablixRowMember0(),
    CreateTablixRowMember1(), }; return tablixMembers; } private
    TablixMemberType CreateTablixRowMember0() { TablixMemberType tmt = new
    TablixMemberType(); tmt.Items = new object[] {
    CreateTablixRowMemberKeepWithGroup(), true, }; tmt.ItemsElementName =
    new ItemsChoiceType72[] { ItemsChoiceType72.KeepWithGroup,
    ItemsChoiceType72.RepeatOnNewPage, }; return tmt; } private
    TablixMemberTypeKeepWithGroup CreateTablixRowMemberKeepWithGroup() {
    return TablixMemberTypeKeepWithGroup.After; } private TablixMemberType
    CreateTablixRowMember1() { TablixMemberType tmt = new
    TablixMemberType(); tmt.Items = new object[] {
    CreateTablixRowMemberGroup() }; tmt.ItemsElementName = new
    ItemsChoiceType72[] { ItemsChoiceType7二.Group }; return tmt; } private
    GroupType CreateTablixRowMemberGroup() { return new GroupType() { Name =
    “详细音信” }; } /// <summary> ///
    ReportDataSource.Name和汉兰达DLC文件的DataSetNamey应保持1致 ///
    对于DataGrid构造的表格,可统一一定用”CustormerDataSet”; ///
    DataSetName无需作为参数字传送进来 /// </summary> ///
    <returns>DataSet Name</returns> private string
    CreateDataSetName() { return String.IsNullOrEmpty(DataSetName) ?
    “CustomerDataSet” : DataSetName; } private StyleType CreateTablixStyle()
    { StyleType st = new StyleType(); st.Items = new object[] {
    CreateTablixBorder() }; st.ItemsElementName = new ItemsChoiceType4[] {
    ItemsChoiceType四.Border }; return st; } // Tablix的异乡框格式 private
    BorderType CreateTablixBorder() { BorderType bt = new BorderType();
    bt.Items = new object[] { “Black”, “Solid”, “2pt” };
    bt.ItemsElementName = new ItemsChoiceType2[] { ItemsChoiceType2.Color,
    ItemsChoiceType2.Style, ItemsChoiceType2.Width }; return bt; }
    #endregion } TablixRdlcGenerator.cscs

 

第三步:提取DataGrid的数据

壹、首要从DataGrid提取每一个Column的Width、BindingPath、Header的Content和种种单元格的数额。数据填充DataTable的Rows,
BindingPath填充DataTable的Columns,

Header的Content用来作为报表Tablix的标题行。BindingPath,对于DataTemplate和DataGridHyperlinkColumn不知道咋个取提取数据.

 

2、dataGrid.ScrollIntoView(dataGrid.Items[rowIndex])那几个是主要。DataGrid用了贰个虚拟啥子来着的(名字不重大,原理简单,Computer领域多量管理品质的都以用这么些点子,

包罗所谓的云啊布满式什么的),就是复用分界面显示,三个窗口里能装下的几十条RowContainer,每趟滚动,人要探望的时候才再一次提取新的要显得的数目。

诸如此类提取数万条记下时,分界面不会卡,也不会占用大多内部存储器,每正是要来得的时候才取几10条,一小点取。要用,才给,只给急需的那一点。

美高梅开户网址 6 ///
<summary> ///
DataGrid的调换器,从DataGrid里提收取数据源,以及HeaderName、Binding的Path和ActualWidth
/// </summary> /// <param
name=”dataGrid”>包括数据的DatGrid</param> /// <param
name=”dt”>DataGrid数据源转变来的DataTable</param> /// <param
name=”headerNames”>DataGridColumn.Header</param> /// <param
name=”bindingPaths”> DataGridBoundColumn.Binding.Path</param>
public static void DataGridAdapter(this DataGrid dataGrid, DataTable dt,
List<string> headerNames, List<string> bindingPaths,
List<double> widths) { //
抽出DataGridColumn的Header,BingdingPath,ActualWidth为布局rdlc文件筹划数据
headerNames.Clear(); bindingPaths.Clear(); widths.Clear(); for (int
index = 0; index < dataGrid.Columns.Count; index++) {
headerNames.Add(dataGrid.Columns[index].Header as string);
widths.Add(dataGrid.Columns[index].ActualWidth); //string
tempBindingPath = ((dataGrid.Columns[index] as
DataGridBoundColumn).Binding as Binding).Path.Path; string
tempBindingPath =
GetDataGridColumnBindingPath(dataGrid.Columns[index]);
bindingPaths.Add(tempBindingPath); if
(String.IsNullOrEmpty(tempBindingPath) == false)
dt.Columns.Add(tempBindingPath, typeof(string)); } for (int rowIndex =
0; rowIndex < dataGrid.Items.Count; rowIndex++) { //
要展现后,才干取到数码 DataGridRow rowContainer =
(DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromIndex(rowIndex);
//
因为Peformance难题,EnableRowVirtualization被设置为true,只加载要展现的多寡
// 重新滚动,然后再任用那几个DataGridRow if (rowContainer == null) {
dataGrid.UpdateLayout();
dataGrid.ScrollIntoView(dataGrid.Items[rowIndex]); rowContainer =
(DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromIndex(rowIndex);
} if (rowContainer != null) { DataGridCellsPresenter presenter =
DataGridHelper.GetVisualChild<DataGridCellsPresenter>(rowContainer);
if (presenter != null) { DataRow dr = dt.NewRow(); bool
isLastRowAllEmpty = true; for (int columnIndex = 0; columnIndex <
bindingPaths.Count; columnIndex++) { DataGridCell cell =
(DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(columnIndex);
if (cell != null) { if (cell.Content is TextBlock) { //TODO:
DataGridHyperlinkColumn取不到数码 dr[bindingPaths[columnIndex]] =
(cell.Content as TextBlock).Text; if
(!String.IsNullOrEmpty((cell.Content as TextBlock).Text))
isLastRowAllEmpty = false; } else if (cell.Content is CheckBox) { string
value = ((cell.Content as CheckBox).IsChecked == true) ? “是” : “否”;
dr[bindingPaths[columnIndex]] = value; } else if (cell.Content is
ComboBox) { dr[bindingPaths[columnIndex]] = (cell.Content as
ComboBox).Text; if (!String.IsNullOrEmpty((cell.Content as
ComboBox).Text)) isLastRowAllEmpty = false; } } } if
(dataGrid.CanUserAddRows && (rowIndex == dataGrid.Items.Count – 1)) { //
要是CanUserAddRows被设置为true,唯有最后一行的数据都不为空(CheckBox不算作内),才把多少增进到DataTable
if (isLastRowAllEmpty) { continue; } } dt.Rows.Add(dr); } } } } 提取DataGrid数据

 

第四步:填充数据

首要在安装ReportViewer类的LocalReport.ReportPath
和LocalReport.DataSources这两项。

美高梅开户网址 7 ///
<summary> /// 报表数据源发生变化时,及时更新显示报表控件的数据源
/// </summary> /// <param
name=”reportDataModel”>报表数据模型基类</param> public void
ResetReportData(ReportDataModel reportDataModel) { if (reportDataModel
美高梅开户网址,!= null) { reportViewer.Reset();
reportViewer.LocalReport.DataSources.Clear(); reportViewer.Clear(); if
(!reportDataModel.IsDataGrid) reportViewer.LocalReport.ReportPath =
reportDataModel.QX56DLCReportPath; else { //
即使是DataGrid转换到的,直接从内存流里加载数据 if
(reportDataModel.MsDataGrid != null) {
reportViewer.LocalReport.LoadReportDefinition(reportDataModel.MsDataGrid);
// 用完就释放掉,流所占用的具备能源 //
reportDataModel.MsDataGrid.Dispose(); } }
reportViewer.LocalReport.DataSources.Add(reportDataModel.ReportDataSource);
reportViewer.RefreshReport(); } } ResetReportData

 

第五步:提供3个ReportHelper类

具体拼接数据以及总结中度等,还有用另壹套办法得以完毕第叁个效益。

1、依据DataGrid每列的增进率,按比例,重新初始化每列的大幅度。

美高梅开户网址 8 一 ///
<summary> 贰 /// 依据DataGrid的Column的Actual
Width来设置报表里对应Tablix的TablixColumn的大幅度 三 /// </summary> 4
/// <param name=”reportWidth”>报表的总拉长率</param> 伍 ///
<param name=”widths”>DataGrid的Column的Actual Width</param>
陆 /// <param
name=”tablixColumnWidths”>重新按百分比估算的TablixColumn的肥瘦列表</param>
7 public static void CalcTablixColumnWidth(string reportWidth,
List<double> widths, out List<string> tablixColumnWidths) 八{ 九 double totalWidth = 0.0; 拾 double originalTotalWidth = 0.0; 11List<double> rateColumnWidth = new List<double>(); 12 string
unit = reportWidth.Substring(reportWidth.Length – 二, 二); 1三 14 //
取到报表宽度字符串除去单位in恐怕cm的数值 1五Double.TryParse(reportWidth.Substring(0, reportWidth.Length – 贰), out
totalWidth); 16 17 1捌 for (int index = 0; index < widths.Count;
index++) 1九 originalTotalWidth += widths[index]; 20 21 22 for (int
index = 0; index < widths.Count; index++) 23
rateColumnWidth.Add(widths[index] / originalTotalWidth); 24 25
tablixColumnWidths = new List<string>(); 26
tablixColumnWidths.Clear(); 27 for (int index = 0; index <
widths.Count; index++) 28
tablixColumnWidths.Add((rateColumnWidth[index] *
totalWidth).ToString() + unit); 29 } CalcTablixColumnWidth

二、把内存中的流读出来,生成对应的TiggoDLC文件,笔者这里没调用。所以设置LocalReport.ReportPath换到reportViewer.LocalReport.LoadReportDefinition(reportDataModel.MsDataGrid);

美高梅开户网址 9 一 ///
<summary> 贰 /// 把内部存款和储蓄器的流生成为rdlc文件 三 /// </summary> 4
/// <param name=”rdlc”>按rdlc格式构形成功的内部存款和储蓄器流</param> 伍public static void Dump途乐dlc(MemoryStream rdlc) 陆 { 7 string temp本田UR-VdlcPath
= AppDomain.CurrentDomain.BaseDirectory +
@”../../../CommonReport/Templates/GeneratedDataGrid.rdlc”; 捌 if
(File.Exists(temp中华VdlcPath)) 九 File.Delete(temp中华VdlcPath); 十 11 using
(FileStream fs = new FileStream(tempGL450dlcPath, FileMode.Create)) 12 { 一三rdlc.WriteTo(fs); 1四 } 15 } Dump普拉多dlc

3、部分调用的代码——给一个简单的EnclaveDLC模板,以提供表头的字体格式和表内部数据等体制相关的新闻,然后再用DataGrid里提取的数目,填充到报表里

美高梅开户网址 10 1 ///
<summary> 二 ///
将DataGrid的数额收取出来,转变来rdlc报表,以促成对提供DataGrid的打字与印刷、预览、分页和页面布局等成效的帮助三 ///
但要求提供2个rdlc报表的模板,必须总结页眉页脚,至少1列多少和标题,以便得到多少的表头的
四 ///
style和数码项的style,那壹列数据项必须是首先项(且第1项的表头和数据都完好无缺提供了style)
五 /// </summary> 6 /// <param
name=”dataGrid”>提供数据的DataGrid</param> 7 /// <param
name=”reportViewer”>要加载DataGrid数据的ReportViewer</param> 8
/// <param
name=”rdlcModelFileName”>rdlc模板的完整路线</param> 九 ///
<param name=”headline”>报表题目</param> 十 public static
void Print(this DataGrid dataGrid, CommonReport.Views.ReportViewer
reportViewer, string rdlcModelFileName, string headline) 1一 { 1二 if
(!File.Exists(rdlcModelFileName)) return; 一叁 1四 //
从DataGrid对应的rdlc模板里读出报表数量来 一5 Report report = null; 1陆string dataSourceName = DatasetName; 17dataGrid.UnderKoleosdlcGenProc(reportViewer, headline, gen => 18 { 1玖report = gen.Read(rdlcModelFileName); 20 2壹 //
ReportDataSource的Name应该用取DataSet的Name 2二 #region 取DataSourceName
23 24 DataGridHelper.ResetRdlcHeadline(report, headline); 25 for (int
index = 0; index < report.Items.Length; index++) 26 { 27 if
(report.Items[index] is DataSetsType) 28 { 29 DataSetsType dataSets =
report.Items[index] as DataSetsType; 30 dataSourceName =
dataSets.DataSet[0].Name; 31 break; 32 } 33 } 34 35 #endregion 3陆 },
(gen, ms, dt) => 三7 { 3八 //
依据从DataGrid里提取的数目再次布局rdlc文件 3玖 奥迪Q5dlcReportAdapter(report,
gen.HeaderNames, gen.FieldNames, gen.Widths); 40 gen.Write(ms, report);
肆一 return new
Microsoft.Reporting.WinForms.ReportDataSource(dataSourceName) { Value =
dt }; 4贰 }); 肆3 } Print

四、打印的有关页面包车型客车一对默许设置(看事态)

美高梅开户网址 11一 //
设置暗中同意打字与印刷布局格局为“展现物理页” 贰reportViewer.SetDisplayMode(DisplayMode.PrintLayout); 三reportViewer.ZoomMode = ZoomMode.Percent; 四 reportViewer.ZoomPercent =
100; 打印设置

伍、TreeView反射那块——成效3

美高梅开户网址 12 1 ///
<summary> 贰 ///
TreeView上摘取的项产生变化时,根据所选TreeViewItem的Header新闻和Tag里所蕴藏的音讯,利用反射构造对应报表的数码类实例
三 /// 加载报表模板,调用委托将数据传到报表的来得控件上 4 ///
</summary> 5 /// <param name=”sender”></param> 陆 ///
<param name=”e”></param> 七 private void
陆风X八dlcTree_SelectedItemChanged(object sender,
RoutedPropertyChangedEventArgs<object> e) 8 { 9 if ((sender !=
null) && (sender is TreeView)) 十 { 11 if ((sender as
TreeView).SelectedItem is TreeViewItem) 1二 { 一三 TreeViewItem tempItem =
(sender as TreeView).SelectedItem as TreeViewItem; 1四 if (tempItem.Tag
is TreeViewItemDataType) 15 { 1陆 TreeViewItemDataType
tempTreeViewDataType = tempItem.Tag as TreeViewItemDataType; 壹7 //
报表类型 1八 if (tempTreeViewDataType.UserControlType ==
TreeViewItemDataType.ControlType.Report) 1玖 { 20 string
reportDataModelInstanceName = tempItem.Header + “Model”; 二一 Type type =
typeof(ReportDataModel); 2二 Assembly assembly = type.Assembly; 23 try 二四{ 25 ReportDataModel reportDataModelInstance =
(ReportDataModel)assembly.CreateInstance(type.Namespace + “.” +
reportDataModelInstanceName); 贰陆 if (reportDataModelInstance != null) 27
{ 28 reportDataModelInstance.RDLCReportPath = (tempItem.Tag as
TreeViewItemDataType).FullPath; 29
reportDataModelInstance.InitDataSource(); 30 if (Viewer != null) 31
Viewer.ResetReportData(reportDataModelInstance); 32 } 33 } 34 catch
(Exception ex) 35 { 36 MessageBox.Show(ex.Message); 37 } 38 } 39 40 //
DataGrid 类型 41 else if (tempTreeViewDataType.UserControlType ==
TreeViewItemDataType.ControlType.DataGrid) 42 { 43 Type type =
this.GetType(); 44 Assembly assembly = type.Assembly; 45 try 46 { 47
UserControl dataGridUserControlInstance =
(UserControl)assembly.CreateInstance(type.Namespace + “.DataGrid.” +
tempItem.Header); 48 } 49 catch (Exception ex) 50 { 51
MessageBox.Show(ex.Message); 52 } 53 } 54 } 55 } 56 } 57 } RdlcTree_SelectedItemChanged

陆、通过VisualTreeHelper找到钦点项目标子或然父的秘诀,可在WPF里通用

美高梅开户网址 13 ///
<summary> /// 搜索子Visual的一定项目标Parent /// </summary>
/// <typeparam name=”T”>钦赐项目</typeparam> /// <param
name=”child”>承袭自Visual的基本控件类型的子Visual</param> ///
<returns></returns> public static T
GetParent<T>(Visual child) where T : Visual { T parent =
default(T); Visual visual = VisualTreeHelper.GetParent(child) as Visual;
parent = visual as T; if (parent == null) return
GetParent<T>(visual); else return parent; } /// <summary>
/// 遍历取父控件的子Viusal,取到钦命项目标子Viusal /// </summary>
/// <typeparam
name=”T”>T是Visual或其子类(基本上WPF的控件都以Visual的子类),钦点子类型</typeparam>
/// <param name=”parent”>父控件</param> ///
<returns>子Viusal</returns> public static T
GetVisualChild<T>(Visual parent) where T : Visual { T child =
default(T); int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < numVisuals; i++) { Visual visual =
(Visual)VisualTreeHelper.GetChild(parent, i); child = visual as T; if
(child == null) child = GetVisualChild<T>(visual); else break; }
return child; } VisualTreeHelper

七、提供一个数量深拷贝的通用方法(C#类以及除基类型之外,大多都以传引用,那几个是地点,值拷贝不佳搞,这一个措施直接拷贝流,可是必须类的种种字段都匡助类别化)

美高梅开户网址 14 一 ///
<summary> 2 ///
对引用类型的数额——“全数字段都加了Serializable天性,以帮忙连串化” 3 ///
利用连串化和反连串化实现深度拷贝,即拷贝了堆上的多寡,搞了个堆的别本 4
/// 而不是浅拷贝那样,只是拷贝了三个针对性数据堆的内部存款和储蓄器地址 5 ///
卓殊实用的小函数,扶助全体引用类型数据 陆 /// </summary> 七 ///
<param name=”original”>要拷贝的引用类型数据源</param> 八 ///
<returns>源数据的副本</returns> 玖 public static object
DeepColne(Object original) 10 { 1一 // 构造3个一时半刻的内部存款和储蓄器流 12 using
(MemoryStream ms = new MemoryStream()) 一三 { 1肆 //
调用BinaryFormatter来达成复杂的连串化和反种类化职业 一五 BinaryFormatter
formatter = new BinaryFormatter(); 16 一7 //
StreamingContext—描述给定的队列化流的源和对象,并提供二个由调用方定义的增大上下文
1八 formatter.Context = new
StreamingContext(StreamingContextStates.Clone); 1九 20 //
把对象图类别化到内部存款和储蓄器流,original的种种字段必须标志为可连串化,不然会出错
贰一 formatter.Serialize(ms, original); 22 二三 //
反种类化从前要求设置流的眼下岗位为最开首的地点 贰四 ms.Position = 0; 25 26
// 把内部存款和储蓄器流反种类化为目的图,再以基类的样式重返给调用者 二七 return
formatter.Deserialize(ms); 28 } 2九 } DeepColne

 

陆、运维作效果果

一、含有DataGrid大概其余控件的分界面

美高梅开户网址 15

二、点击打字与印刷后,报表生成

美高梅开户网址 16

附:

1、ReportItems!具体汉兰达DLC报表上控件的名称.Value这几个取到报表设计器里任性项的多寡,然后就可在表明式里张开各个逻辑运算。例如:

= ReportItems!forestryMaintenance.Value + ReportItems!pension.Value +
ReportItems!SumPolicy.Value

  • ReportItems!livingExpenses.Value + ReportItems!resettlement.Value

贰、合并单元格,纵向和横向的

其1要分组,具体请寻觅网络能源

叁、调节每页都展现

对此标题,设置KeepWith属性和Tablix一同出现就好;还有一个主意,是安装任何的性质,权且忘了,网上有

四、XML很关键,据近日所知,微软的工程文件、WPF、打字与印刷、报表、XPS、Office200七过后版本等,XML都是基本。(未完,待续)

五、页面纸张尺寸(PageSetting里的部分关于大小的值,单位都以一成0
inch;页面设置布局排版打字与印刷有点麻烦,稍不检点就多出来一点,字体、页眉、页脚、边框、页边距等),如下图:

美高梅开户网址 17

 6、border style

美高梅开户网址 18

 

末尾,必须感激和致意蜡人张前辈:

二.微软GotReportViewer官方的案例:

上二个月,做了本田UR-VDLC报表,首固然叁块作用:
一、从DataGrid提取(包蕴新型的增加和删除改)的数量,自动生…

引言: 从前在web项目中用到报表的时候 大家利用的是ReportServices
(服务器端的)

一、从DataGrid提取(蕴含新型的增加和删除改)的数码,自动生成对应的安德拉DLC报表文件(以流的款型驻存在内部存款和储蓄器中),用ReportViewer类来呈现、打字与印刷、排版、预览、分页

运用成效还可以够 缺点是: 须要在Sqlserver200伍里面创设报表(要求 运转报表服务
设置权限等很麻烦)

一-一、提供2个领取大四控件数据的通用接口,然后拼接成DataTable那种网状的格子。DataGrid里修改、扩张、删除等数码变动,立刻联合立异到报表

倍感不及在程序里面来的直接和福利(之前一贯未曾找到方法)

二、给八个简约的途锐DLC模板,提供表头的书体格式和表内部数据等体制相关的音讯,然后再用DataGrid里提取的数量,生成DataTable后其它必需音信,填充到报表里,

间接到2010年初,一家客户 装的是Sqlserver2009 (原来做的自行发布报表
使用的是Sqlserver里面包车型地铁一对Webservices函数)

活动调治报表格式

但Sqlserver二零零六里面未有这几个措施了 (唯有接口的名称 未有得以达成)

3、做了2个TreeView,非常粗略;遵照报表文件名称,切换左侧TreeView的Item,就加载不一样的报表,彰显数据。用了一些反光的学识

大家报表的全自动发布无法做了 只得展开Sqlserver 一个一个报表加多的
(郁闷…)

 

新兴 我们三个同事(李来)做的Web报表(rdlc格式) 在本地做的(Web工程里面)
未有运用Sqlserver 里面包车型客车

 

如此那般就很方便了 上边小编举个例子说美赞臣(Meadjohnson)下用法:

第三步:依照 Report Definition Language (本田UR-VDL) 生成对应的类和命名空间。

壹.  确立1个文书夹(就举个例证是LANDDLC文件夹吧)

1、去
下载ReportDefinition2010.xsd。

在项目上 右键采纳丰盛/新建项 /报表 (新确立1个rdlc文件)

瞩目:ReportDefinition和Visual
Studio发布的有个日子差,官英特网有ReportDefinition2005版和ReportDefinition2008版。ReportDefinition2005版,VS二〇〇九及以往才支撑;

至于那几个文件怎么使用  和 服务器端的(Sqlserver)一样 我省略….

ReportDefinition二零零六版,VS2010及将来匡助。20拾版,要VS二零一二之后才支撑。作者的是VS20十,用ReportDefinition二〇〇九版就好。

数据源使用( 第三步创立的XSD数据源 在底下会有介绍 )

 

  1. 创设多个文书夹(就举个例证是XSD文件夹吧)

2、找XML Schema Definition Tool
(Xsd.exe),Windows操作系统会自带(微软会自带好多作用庞大的exe,借使开源就好了)。For
more detail,please refer to:

在项目上 右键选拔充分/新建项 /数据集 (新成立一个xsd文件)

官方网址有详尽的下令使用表明

美高梅开户网址 19

 Below is my CMD in administator mode:

在那个目前表里面扩展列

C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\x64>xsd

  1. 新确立三个aspx网页 选拔ReportViewer 控件

/c /n:RDLC  

<%@ Register Assembly=”Microsoft.ReportViewer.WebForms,
Version=9.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a”
    Namespace=”Microsoft.Reporting.WebForms” TagPrefix=”rsweb” %>

/out:C:\Users\admin\Desktop\RDLCReportResearch

  <rsweb:ReportViewer ID=”ReportViewer1″ runat=”server”
Font-Names=”Verdana” Font-Size=”8pt”
        Height=”400px” Width=”400px”>
        <LocalReport>
        </LocalReport>
    </rsweb:ReportViewer>

C:\Users\admin\Desktop\RDLCReportResearch\ReportDefinition.xsd

  1. 在后台代码里面

 完了,生成的是如此个样板(ReportDefinition200五的扭转出来有七千行左右,ReportDefinition二〇〇八的及事后有一千0多行,贴1部分,样子参照下面代码)

            ReportViewer1.LocalReport.ReportPath =
@”rdlc\Report1.rdlc”;

美高梅开户网址 20美高梅开户网址 21

            //怎么着传参数

using System.Xml.Serialization;


    /// <remarks/>
    [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.3038")]
    [System.SerializableAttribute()]
    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true, Namespace="http://schemas.microsoft.com/sqlserver/reporting/2008/01/reportdefinition")]
    [System.Xml.Serialization.XmlRootAttribute(Namespace="http://schemas.microsoft.com/sqlserver/reporting/2008/01/reportdefinition", IsNullable=false)]
    public partial class Report {

        private object[] itemsField;

        private ItemsChoiceType80[] itemsElementNameField;

        private System.Xml.XmlAttribute[] anyAttrField;

        /// <remarks/>
        [System.Xml.Serialization.XmlAnyElementAttribute()]
        [System.Xml.Serialization.XmlElementAttribute("Author", typeof(string))]
        [System.Xml.Serialization.XmlElementAttribute("AutoRefresh", typeof(uint))]
        [System.Xml.Serialization.XmlElementAttribute("Body", typeof(BodyType))]
        [System.Xml.Serialization.XmlElementAttribute("Classes", typeof(ClassesType))]
        [System.Xml.Serialization.XmlElementAttribute("Code", typeof(string))]
        [System.Xml.Serialization.XmlElementAttribute("CodeModules", typeof(CodeModulesType))]
        [System.Xml.Serialization.XmlElementAttribute("ConsumeContainerWhitespace", typeof(bool))]

            ReportParameter myParameter = new ReportParameter(“参数0一”,
“参数的值”);
            ReportParameter[] myParameterList = { myParameter };

ReportDefinition.cs

            ReportViewer1.LocalReport.SetParameters(myParameterList);
            //

 

            //DataSet1_DataTable1 指的是报表文件中数据源的称号

第二步:创建RDLCGenerator类和TablixRDLCGenerator类

    //myDataSet 指的是数据源(就是你从数据Curry面查询出来的数额)

1、依照下载的Report Definition
Language(昂科威DL)和二个开立的简练的本田UR-VDLC文件,知道途达DLC文件核心要有哪几部分构成;然后层层嵌套创制就出去了,很简短。

            ReportDataSource rds = new
ReportDataSource(“DataSet1_DataTable1”, myDataSet.Tables[0]);
            ReportViewer1.LocalReport.DataSources.Clear();
            ReportViewer1.LocalReport.DataSources.Add(rds);
            ReportViewer1.LocalReport.Refresh();

贰-壹、Tablix是关键数据区,GotReportViewer上面包车型地铁例证,DynamicMatrix和DynamicTable是依照智跑DL200伍来做的,SportageDL二零零六以后,便是三个Tablix:

  1. 假诺不了然报表的数据源的称呼的话

贰-2、Tablix的主要性数据区域: TablixHierarchyType
CreateTablixColumnHierarchy()和TablixHierarchyType
CreateTablixRowHierarchy()

  您在aspx页面上 单击ReportViewer壹的右上角 选拔三个当地数据源
/选拔数据源

2-三、对于HeaderRow和DataRow关键就在上面包车型客车区别。

美高梅开户网址 22

美高梅开户网址 23美高梅开户网址 24

其间的报表数量源 正是数据源的称谓

1         private LocIDStringWithDataTypeAttribute CreateTablixTextRunValue(bool isHeaderCell, string name)
2         {
3             LocIDStringWithDataTypeAttribute v = new LocIDStringWithDataTypeAttribute();
4             v.Value = isHeaderCell ? name : "=Fields!" + name + ".Value";
5             v.DataType = StringWithDataTypeAttributeDataType.String;
6             return v;
7         }

结束语:

CreateTablixTextRunValue

到此 就足以试运作一下你的web报表了

 二-4、DataSet的名字自然要和ReportDataSource里的名字完全协作

其一表格仍是可以够直接在网页里面调用客户端的打字与印刷机(在vs20拾里面试验的)

 

201一年四月二十三日1九:3八:55 过了少数天 再补偿一下:

卡宴dlcGenerator的Read和Write方法相比较主要。

<一> XSD文件的文书夹好像有需求 假若放置2个文本夹里面
就找不到 xsd数据源(不应当啊) 不过这么些细节也是个经验

美高梅开户网址 25美高梅开户网址 26

<贰> 报表的DLL版本的难标题前晋升公司的贰个项目(从VS二〇一〇->VS2010)
报表(ReportingServices)从⑧.0->十.0

    /// table + matrix = tablix
    /// Microsoft 用一个tablix来支持Table(表), Matrix(矩阵) and List(列表)这三种报表项
    /// 整合了table和matrix的功能

     须求留意的是:引用里面增添ReportingServices WebForm 十.0版本

View Code

                      在页面上 也是运用十.0
在Web.config文件之中一样使用这么些版本

美高梅开户网址 27美高梅开户网址 28

       #region Properties

        // DataGrid 的DataGridColumn的Header
        private List<string> headerNames = new List<string>();
        public List<string> HeaderNames
        {
            get { return headerNames; }
        }

        // 对应DataGrid Binding的Path
        private List<string> fieldNames = new List<string>();
        public List<string> FieldNames
        {
            get { return fieldNames; }
        }

        // 对应DataGrid Column的ActualWdith(因为实际的窗口宽度会重新计算)
        private List<double> widths = new List<double>();
        public List<double> Widths
        {
            get { return widths; }
        }

        // 如果没有更新过页面设置,用ReportViewer的默认页面设置;否则用最新的页面设置
        public PageSettings PageSettings { get; set; }

        public string Headline { get; set; }

        public string DataSourceName { get; set; }

        public string DataSetName { get; set; }

        #endregion

        #region Methods

        // 一层套一层,把xml构造出来
        private Report CreateReport()
        {
            Report report = new Report();

            report.Items = new object[]
            {
                CreateDataSources(),
                CreateDataSets(),
                CreateBody(),
                CalcReportWidth(),
                CreatePage(),
            };
            report.ItemsElementName = new ItemsChoiceType80[]
            {
                ItemsChoiceType80.DataSources,
                ItemsChoiceType80.DataSets,
                ItemsChoiceType80.Body,
                ItemsChoiceType80.Width,
                ItemsChoiceType80.Page,
            };

            return report;
        }

        private DataSourcesType CreateDataSources()
        {
            DataSourcesType dataSources = new DataSourcesType();
            dataSources.DataSource = new DataSourceType[] { CreateDataSource() };
            return dataSources;
        }

        private DataSourceType CreateDataSource()
        {
            DataSourceType dataSource = new DataSourceType();
            dataSource.Name = String.IsNullOrEmpty(DataSetName) ? "TBReport" : DataSetName;
            dataSource.Items = new object[] { CreateDataSourceConnectionProperties() };
            return dataSource;
        }

        private ConnectionPropertiesType CreateDataSourceConnectionProperties()
        {
            ConnectionPropertiesType connectionProperties = new ConnectionPropertiesType();

            connectionProperties.Items = new object[]
            {
                "System.Data.DataSet",
                "/* Local Connection */",
            };
            connectionProperties.ItemsElementName = new ItemsChoiceType[]
            {
                ItemsChoiceType.DataProvider,
                ItemsChoiceType.ConnectString,
            };

            return connectionProperties;
        }

        private DataSetsType CreateDataSets()
        {
            DataSetsType dataSets = new DataSetsType();
            dataSets.DataSet = new DataSetType[] { CreateDataSet() };
            return dataSets;
        }

        // Query暂时就不要了
        private DataSetType CreateDataSet()
        {
            DataSetType dataSet = new DataSetType();
            // DataSetName写死就好
            dataSet.Name = "CustomerDataSet";
            dataSet.Items = new object[] 
            { 
                CreateDataSetFields(),
                CreateDataSetQuery(),
            };

            return dataSet;
        }

        private FieldsType CreateDataSetFields()
        {
            FieldsType fields = new FieldsType();

            // DataSet的具体field由DataGrid的Bingding的Path值决定
            if ((fieldNames != null) && (fieldNames.Count > 0))
            {
                fields.Field = new FieldType[fieldNames.Count];
                for (int index = 0; index < fieldNames.Count; index++)
                    fields.Field[index] = CreateDataSetField(fieldNames[index]);
            }

            return fields;
        }

        private FieldType CreateDataSetField(string fieldName)
        {
            FieldType field = new FieldType();
            field.Name = fieldName;
            field.Items = new object[]
            {
                fieldName,
                // CreateDataSetFieldValue(),
            };
            return field;
        }

        // 暂时DataType全部用String
        private StringWithDataTypeAttribute CreateDataSetFieldValue()
        {
            StringWithDataTypeAttribute value = new StringWithDataTypeAttribute();
            value.DataType = StringWithDataTypeAttributeDataType.String;
            return value;
        }

        private QueryType CreateDataSetQuery()
        {
            QueryType query = new QueryType();

            query.Items = new object[]
            {
                "TBReport",
                "/* Local Query */",
            };
            query.ItemsElementName = new ItemsChoiceType1[]
            {
                ItemsChoiceType1.DataSourceName,
                ItemsChoiceType1.CommandText,
            };

            return query;
        }

        private BodyType CreateBody()
        {
            BodyType body = new BodyType();

            body.Items = new object[]
            {
                "4.8in",                // Height
                CreateReportItems(),    // ReportItems
                CreateBodyStyle(),
            };
            return body;
        }


        private ReportItemsType CreateReportItems()
        {
            ReportItemsType reportItems = new ReportItemsType();

            // 这是关键数据区域
            TablixRdlcGenerator tablixGen = new TablixRdlcGenerator();
            tablixGen.ResetHeaderNames(HeaderNames);
            tablixGen.ResetFieldNames(FieldNames);

            List<string> tablixColumnWidths;
            DataGridHelper.CalcTablixColumnWidth(CalcReportWidth(), Widths, out tablixColumnWidths);
            tablixGen.ResetWidths(tablixColumnWidths);

            reportItems.Items = new object[] 
            { 
                CreateReportHeadlineTextbox(),
                tablixGen.CreateTablix()
            };


            return reportItems;
        }

        // 创建标题
        private TextboxType CreateReportHeadlineTextbox()
        {
            TextboxType headlineTextbox = new TextboxType();
            headlineTextbox.Name = "headlineTextbox";

            string left = (PageSettings == null) ? "2cm" : ((double)PageSettings.Margins.Left / 100.0).ToString() + "in";
            string width = (PageSettings == null) ? "17cm" :
                ((double)(PageSettings.PaperSize.Width - PageSettings.Margins.Left - PageSettings.Margins.Right) / 100.0).ToString() + "in";

            headlineTextbox.Items = new object[]
            {
                true,
                true,
                CreateHeadlineTextboxParagraphs(),
                left,
                "0.5cm",
                "1.0cm",
                width,
                CreateHeadlineTextboxStyle()

            };
            headlineTextbox.ItemsElementName = new ItemsChoiceType14[]
            {   
                ItemsChoiceType14.CanGrow,
                ItemsChoiceType14.KeepTogether,
                ItemsChoiceType14.Paragraphs,
                ItemsChoiceType14.Left,
                ItemsChoiceType14.Top,
                ItemsChoiceType14.Height,
                ItemsChoiceType14.Width,
                ItemsChoiceType14.Style
            };

            return headlineTextbox;
        }

        private ParagraphsType CreateHeadlineTextboxParagraphs()
        {
            ParagraphsType headlineParagraphs = new ParagraphsType();
            headlineParagraphs.Paragraph = new ParagraphType[] {CreateHeadlineTextboxParagraph()};
            return headlineParagraphs;
        }

        private ParagraphType CreateHeadlineTextboxParagraph()
        {
            ParagraphType pt = new ParagraphType();
            pt.Items = new object[]
            {
                CreateHeadlineTextRuns(),
                CreateHeadlineParagraphStyle()
            };
            pt.ItemsElementName = new ItemsChoiceType12[]
            {
                ItemsChoiceType12.TextRuns,
                ItemsChoiceType12.Style,
            };
            return pt;
        }

        private TextRunsType CreateHeadlineTextRuns()
        {
            TextRunsType trt = new TextRunsType();
            trt.TextRun = new TextRunType[] { CreateHeadlineTextRun() };
            return trt;
        }

        private TextRunType CreateHeadlineTextRun()
        {
            TextRunType trt = new TextRunType();

            trt.Items = new object[]
            {
                CreateHeadLineTextRunValue(),
                CreateHeadlineTextRunStyle()
            };
            trt.ItemsElementName = new ItemsChoiceType11[]
            {
                ItemsChoiceType11.Value,
                ItemsChoiceType11.Style
            };

            return trt;
        }

        private LocIDStringWithDataTypeAttribute CreateHeadLineTextRunValue()
        {
            LocIDStringWithDataTypeAttribute value = new LocIDStringWithDataTypeAttribute();
            value.Value = (Headline == null) ? "标题" : Headline;
            value.DataType = StringWithDataTypeAttributeDataType.String;
            return value;
        }

        private StyleType CreateHeadlineTextRunStyle()
        {
            StyleType st = new StyleType();

            st.Items = new object[]
            {
                "宋体",
                "14pt",
                "Bold",
            };
            st.ItemsElementName = new ItemsChoiceType4[]
            {
                ItemsChoiceType4.FontFamily,
                ItemsChoiceType4.FontSize,
                ItemsChoiceType4.FontWeight
            };

            return st;
        }

        private StyleType CreateHeadlineParagraphStyle()
        {
            StyleType st = new StyleType();
            st.Items = new object[] { "Center" };
            st.ItemsElementName = new ItemsChoiceType4[] { ItemsChoiceType4.TextAlign };
            return st;
        }

        private StyleType CreateHeadlineTextboxStyle()
        {
            StyleType headlineStyle = new StyleType();

            headlineStyle.Items = new object[]
            {
                 CreateHeadlineTextboxBorder(),
                "2pt",
                "2pt",
                "2pt",
                "2pt"
            };
            headlineStyle.ItemsElementName = new ItemsChoiceType4[]
            {
                ItemsChoiceType4.Border,
                ItemsChoiceType4.PaddingLeft,
                ItemsChoiceType4.PaddingRight,
                ItemsChoiceType4.PaddingTop,
                ItemsChoiceType4.PaddingBottom
            };

            return headlineStyle;
        }

        private BorderType CreateHeadlineTextboxBorder()
        {
            BorderType headlineTextboxBorder = new BorderType();
            headlineTextboxBorder.Items = new object[] { "None" };
            headlineTextboxBorder.ItemsElementName = new ItemsChoiceType2[] { ItemsChoiceType2.Style };
            return headlineTextboxBorder;
        }

        private StyleType CreateBodyStyle()
        {
            return new StyleType();
        }

        /// <summary>
        /// 设置页面基本属性—页眉、页脚、页宽、页高、左边距、右边距等
        /// </summary>
        private PageType CreatePage()
        {
            PageType page = new PageType();

            // 根据微软官方文档,PaperSize.Height, PaperSize.Width and Margins的Left, Right, Top, Bottom are in hundredths of an inch.
            string pageHeight = (PageSettings == null) ? "29.7cm" : ((double)PageSettings.PaperSize.Height / 100.0).ToString() + "in";
            string pageWidth = (PageSettings == null) ? "21cm" : ((double)PageSettings.PaperSize.Width / 100.0).ToString() + "in";
            string leftMargin = (PageSettings == null) ? "2cm" : ((double)PageSettings.Margins.Left / 100.0).ToString() + "in";
            string rightMargin = (PageSettings == null) ? "2cm" : ((double)PageSettings.Margins.Right / 100.0).ToString() + "in";
            string topMargin = (PageSettings == null) ? "2cm" : ((double)PageSettings.Margins.Top / 100.0).ToString() + "in";
            string bottomMargin = (PageSettings == null) ? "2cm" : ((double)PageSettings.Margins.Bottom / 100.0).ToString() + "in";

            // TODO:
            // 页眉、页脚(后面再做)
            page.Items = new object[]
            {
                //创建Header不能为空
                // CreatePageHeader(),
                pageHeight,
                pageWidth,
                leftMargin,
                rightMargin,
                topMargin,
                bottomMargin,
                "0.13cm",
            };
            page.ItemsElementName = new ItemsChoiceType77[]
            {
               // ItemsChoiceType77.PageHeader,
                ItemsChoiceType77.PageHeight,
                ItemsChoiceType77.PageWidth,
                ItemsChoiceType77.LeftMargin,
                ItemsChoiceType77.RightMargin,
                ItemsChoiceType77.TopMargin,
                ItemsChoiceType77.BottomMargin,
                ItemsChoiceType77.ColumnSpacing
            };

            return page;
        }

        /// <summary>
        /// PageHeader和PageFooter也只是TextRun里Value的数据不一样
        /// </summary>
        /// <returns></returns>
        private PageSectionType CreatePageHeader()
        {
            return new PageSectionType();
        }

        private PageSectionType CreatePageFooter()
        {
            return new PageSectionType();
        }

        /// <summary>
        /// 把Report序列化为流
        /// </summary>
        /// <param name="stream">根据Report序列化好的流</param>
        public void Write(Stream stream)
        {
            Write(stream, CreateReport());
        }

        public void Write(Stream stream, Report report)
        {
            new XmlSerializer(typeof(Report)).Serialize(stream, report);
        }

        public Report Read(Stream stream)
        {
            return (Report)new XmlSerializer(typeof(Report)).Deserialize(stream);
        }

        /// <summary>
        /// 把和DataGrid对应的rdlc模板文件反序列化为Report
        /// </summary>
        /// <param name="rdlcModelFilePath">和DataGrid对应的rdlc模板文件</param>
        /// <returns>反序列化之后的Report</returns>
        public Report Read(string rdlcModelFilePath)
        {
            using (var stream = new FileStream(rdlcModelFilePath, FileMode.Open))
            {
                return Read(stream);
            }
        }

        public void Write(string rdlcModelFilePath)
        {
            using (var stream = new FileStream(rdlcModelFilePath, FileMode.OpenOrCreate))
            {
                stream.SetLength(0);
                Write(stream);
            }
        }

        /// <summary>
        /// 计算Report的宽度,页宽 - 左边距 - 右边距
        /// </summary>
        /// <returns></returns>
        public string CalcReportWidth()
        {
            string reportWidth = String.Empty;
            const double size = 100.0;
            reportWidth = (PageSettings == null) ? "6.5in" :
                ((double)(PageSettings.PaperSize.Width - PageSettings.Margins.Left - PageSettings.Margins.Right) / size).ToString() + "in";
            return reportWidth;
        }

RdlcGenerator.cs

美高梅开户网址 29美高梅开户网址 30

    public class TablixRdlcGenerator
    {
        #region Properties

        // DataGrid 的DataGridColumn的Header
        private List<string> headerNames = new List<string>();
        public List<string> HeaderNames { get { return headerNames; } }

        // 对应DataGrid Binding的Path
        private List<string> fieldNames = new List<string>();
        public List<string> FieldNames { get { return fieldNames; } }
        public string DataSetName { get; set; }

        // 对应DataGrid Column的ActualWidth
        private List<string> widths = new List<string>();
        public List<string> Widths
        {
            get { return widths; }
        }


        #endregion

        #region Methods

        private void ResetValues(List<string> p, List<string> v)
        {
            p.Clear();
            if (v != null)
            {
                p.AddRange(v);
            }
        }

        public void ResetHeaderNames(List<string> hns)
        {
            ResetValues(HeaderNames, hns);
        }

        public void ResetFieldNames(List<string> fns)
        {
            ResetValues(FieldNames, fns);
        }

        public void ResetWidths(List<string> widths)
        {
            ResetValues(Widths, widths);
        }

        /// <summary>
        /// 矩阵和Table对应的Tablix稍微有些不一样,如对于矩阵,TablixBody里的表头和数据项
        /// 一些值会拆分到TablixColumnHierarchy和TablixRowHierarchy里TablixMember--TablixHeader--CellContents--Textbox
        /// 对于DataGrid我们用最简单的Table就好
        /// </summary>
        /// <returns></returns>
        public TablixType CreateTablix()
        {
            TablixType tablix = new TablixType();
            tablix.Name = "dataGridTablix0";
            tablix.Items = new object[]
            {
               // 创建TablixCorner不能创建个空的
               // CreateTablixCorner(),
                CreateTablixBody(),
                CreateTablixColumnHierarchy(),
                CreateTablixRowHierarchy(),
                true,
                true,
                CreateDataSetName(),
                // Top, Left, Height, Width可具体调整
                // Top, Left ---> Location(距离左上角);Height, Width ---> Size
                // (Tablix的大小,这个Width不管用,具体是由各个TablixColumn的Width之和决定)
                "1.8cm",
                "2cm",
                "2cm",     
                "17cm",
                CreateTablixStyle(),
            };
            tablix.ItemsElementName = new ItemsChoiceType73[]
            {
               // ItemsChoiceType73.TablixCorner,
                ItemsChoiceType73.TablixBody,
                ItemsChoiceType73.TablixColumnHierarchy,
                ItemsChoiceType73.TablixRowHierarchy,
                ItemsChoiceType73.RepeatColumnHeaders,
                ItemsChoiceType73.RepeatRowHeaders,
                ItemsChoiceType73.DataSetName,
                ItemsChoiceType73.Top,
                ItemsChoiceType73.Left,
                ItemsChoiceType73.Height,
                ItemsChoiceType73.Width,
                ItemsChoiceType73.Style
            };

            return tablix;
        }

        /// <summary>
        /// non-essential element, so make it emtpy temprorily
        /// 看样子是表头行,纵向合并的单元格(如纵向两行合并为一行)等相关的
        /// </summary>
        /// <returns></returns>
        private TablixCornerType CreateTablixCorner()
        {
            return new TablixCornerType();
        }

        private TablixBodyType CreateTablixBody()
        {
            TablixBodyType tablixBody = new TablixBodyType();
            tablixBody.Items = new object[]
            {
                CreateTablixColumns(),
                CreateTablixRows(),
            };
            return tablixBody;
        }

        private void EnumHeaderNames(Action<int> act)
        {
            for (int i = 0; i < HeaderNames.Count; i++)
            {
                act(i);
            }
        }

        private TablixColumnsType CreateTablixColumns()
        {
            TablixColumnsType tablixColumns = new TablixColumnsType();

            // 根据DataGridColumns的数量来决定创建几列,并且每列要把具体的宽度传进去
            tablixColumns.Items = new object[headerNames.Count];
            EnumHeaderNames(p =>
            {
                tablixColumns.Items[p] = CreateTablixColumn(p);
            });
            return tablixColumns;
        }

        private TablixColumnType CreateTablixColumn(int index)
        {
            // Width of column,应该根据DataGridColumn.Width来具体设定,暂时给个固定值
            return new TablixColumnType() { Items = new object[] { Widths[index] } };
        }

        /// <summary>
        /// 对于DataGrid只应有两行,一行是Header,一行是数据
        /// 如果有求
        /// </summary>
        /// <returns>TablixRowsType</returns>
        private TablixRowsType CreateTablixRows()
        {
            TablixRowsType tablixRows = new TablixRowsType();
            tablixRows.Items = new object[]
            {
                CreateTablixRowHeader(),
                CreateTablixRowData(),
            };
            return tablixRows;
        }

        private TablixRowType CreateTablixRowType(bool isHeader)
        {
            TablixRowType trt = new TablixRowType();
            trt.Items = new object[]
            {
                "0.23622in",    // Default height
                CreateTablixCells(isHeader),    // Header的Cells的内容和Data的Cells的内容应该不同
            };
            return trt;
        }

        /// <summary>
        /// Tablix Header
        /// </summary>
        /// <returns></returns>
        private TablixRowType CreateTablixRowHeader()
        {
            return CreateTablixRowType(true);
        }

        private TablixRowType CreateTablixRowData()
        {
            return CreateTablixRowType(false);
        }

        private TablixCellsType CreateTablixCells(bool isHeaerCell)
        {
            TablixCellsType tablixCells = new TablixCellsType();
            // 根据DataGridColumns的数量来决定创建几个Cell, Header应传DataGridColumn.Header数据
            tablixCells.Items = new object[HeaderNames.Count];
            EnumHeaderNames(p =>
            {
                tablixCells.Items[p] = CreateTablixCell(isHeaerCell, p);
            });
            return tablixCells;
        }

        private TablixCellType CreateTablixCell(bool isHeaderCell, int index)
        {
            TablixCellType tablixCell = new TablixCellType();
            // 基本的只要"CellContents"就够了
            tablixCell.Items = new object[] { CreateCellContentes(isHeaderCell, index) };
            return tablixCell;
        }

        private CellContentsType CreateCellContentes(bool isheaderCell, int index)
        {
            CellContentsType cellContents = new CellContentsType();

            // 对于DataGrid转换的rdlc,通常是一个Textbox。具体可以是Chart、Image、Line、Rectangle、Subreport等等
            cellContents.Items = new object[] { CreateTablixCellTextbox(isheaderCell, index) };
            cellContents.ItemsElementName = new ItemsChoiceType71[] { ItemsChoiceType71.Textbox };

            return cellContents;
        }

        private TextboxType CreateTablixCellTextbox(bool isHeaderCell, int index)
        {
            TextboxType tablixCellTextbox = new TextboxType();
            // 对于Header的Textbox可以复杂一点,多些字体、背景颜色等字段的定义
            // Data的简单点//isHeaderCell ? headerNames[index] : 
            tablixCellTextbox.Name = isHeaderCell ? "TB" + fieldNames[index] : fieldNames[index];
            tablixCellTextbox.Items = new object[]
            {
                true,
                true,
                CreateTablixCellTextboxParagraphs(isHeaderCell, isHeaderCell ? headerNames[index] : fieldNames[index]),
                CreateTablixCellTextboxStyle(),
            };
            tablixCellTextbox.ItemsElementName = new ItemsChoiceType14[]
            {
                ItemsChoiceType14.CanGrow,
                ItemsChoiceType14.KeepTogether,
                ItemsChoiceType14.Paragraphs,
                ItemsChoiceType14.Style,
            };
            return tablixCellTextbox;
        }

        private ParagraphsType CreateTablixCellTextboxParagraphs(bool isHeaderCell, string name)
        {
            ParagraphsType pt = new ParagraphsType();
            pt.Paragraph = new ParagraphType[] { CreateTablixCellTextboxParagraph(isHeaderCell, name) };
            return pt;
        }

        private ParagraphType CreateTablixCellTextboxParagraph(bool isHeaderCell, string name)
        {
            ParagraphType pt = new ParagraphType();
            pt.Items = new object[]
            {
                CreateTablixCellTextboxParagraphTextRuns(isHeaderCell, name),
                CreateTablixCellTextboxParagraphStyle(isHeaderCell),
            };
            pt.ItemsElementName = new ItemsChoiceType12[]
            {
                ItemsChoiceType12.TextRuns,
                ItemsChoiceType12.Style,
            };
            return pt;
        }

        private TextRunsType CreateTablixCellTextboxParagraphTextRuns(bool isHeaderCell, string name)
        {
            TextRunsType trt = new TextRunsType();
            trt.TextRun = new TextRunType[] { CreateTablixCellTextboxParagraphTextRun(isHeaderCell, name) };
            return trt;
        }

        private TextRunType CreateTablixCellTextboxParagraphTextRun(bool isHeaderCell, string name)
        {
            TextRunType trt = new TextRunType();
            trt.Items = new object[]
            {
                CreateTablixTextRunValue(isHeaderCell, name),
                CreateTablixTextRunStyle(isHeaderCell),
            };
            trt.ItemsElementName = new ItemsChoiceType11[]
            {
                ItemsChoiceType11.Value,
                ItemsChoiceType11.Style,
            };
            return trt;
        }

        // 数据项和Header的关键不一样就在这个了
        private LocIDStringWithDataTypeAttribute CreateTablixTextRunValue(bool isHeaderCell, string name)
        {
            LocIDStringWithDataTypeAttribute v = new LocIDStringWithDataTypeAttribute();
            v.Value = isHeaderCell ? name : "=Fields!" + name + ".Value";
            v.DataType = StringWithDataTypeAttributeDataType.String;
            return v;
        }

        private StyleType CreateTablixTextRunStyle(bool isHeaderCell)
        {
            StyleType st = new StyleType();
            string fontSize = isHeaderCell ? "11pt" : "10pt";
            string FontWeight = isHeaderCell ? "Bold" : "Default";
            st.Items = new object[]
            {
                "宋体",
                fontSize,
                FontWeight,
            };
            st.ItemsElementName = new ItemsChoiceType4[]
            {
                 ItemsChoiceType4.FontFamily,
                 ItemsChoiceType4.FontSize,
                 ItemsChoiceType4.FontWeight,
            };
            return st;
        }

        // 暂时设为表头行“居中对齐”,数据行“靠左对齐”;后面可具体定制表头行和数据行的对齐方式
        private StyleType CreateTablixCellTextboxParagraphStyle(bool isHeaderCell)
        {
            StyleType st = new StyleType();
            st.Items = new object[] { isHeaderCell ? "Center" : "Left" };
            st.ItemsElementName = new ItemsChoiceType4[] { ItemsChoiceType4.TextAlign };
            return st;
        }

        // *****************************
        // Header的Color和Style可以和数据不同,下面是默认的Sytle,可自定义
        //******************************
        private StyleType CreateTablixCellTextboxStyle()
        {
            StyleType st = new StyleType();
            st.Items = new object[]
            {
                 CreateTablixCellTextboxBorder(),
                 "2pt",
                 "2pt",
                 "2pt",
                 "2pt",
            };
            st.ItemsElementName = new ItemsChoiceType4[]
            {
                ItemsChoiceType4.Border,
                // ItemsChoiceType4.BackgroundColor, 默认数据没有BackgroundColor
                ItemsChoiceType4.PaddingLeft,
                ItemsChoiceType4.PaddingRight,
                ItemsChoiceType4.PaddingTop,
                ItemsChoiceType4.PaddingBottom,
            };
            return st;
        }

        private BorderType CreateTablixCellTextboxBorder()
        {
            BorderType bt = new BorderType();
            bt.Items = new object[]
            {
                "Black",
                "Solid",
                "1pt"
            };
            bt.ItemsElementName = new ItemsChoiceType2[]
            {
                ItemsChoiceType2.Color,
                ItemsChoiceType2.Style,
                ItemsChoiceType2.Width
            };
            return bt;
        }

        /// <summary>
        /// 按最简单的来,DataGrid对应的应该是有几个column创建几个TablixMember
        /// </summary>
        private TablixHierarchyType CreateTablixColumnHierarchy()
        {
            return new TablixHierarchyType() { Items = new object[] { CreateTablixColumnMembers() } };
        }

        private TablixMembersType CreateTablixColumnMembers()
        {
            TablixMembersType tmts = new TablixMembersType();
            tmts.TablixMember = new TablixMemberType[HeaderNames.Count];
            EnumHeaderNames(p =>
            {
                tmts.TablixMember[p] = CreateTablixColumnMember();
            });
            return tmts;
        }

        // DataGrid的Column对应的TablixMember创建一个空的就行
        private TablixMemberType CreateTablixColumnMember()
        {
            return new TablixMemberType();
        }

        // DataGrid按最简单的默认的来,即创建2个TablixMember即可
        private TablixHierarchyType CreateTablixRowHierarchy()
        {
            return new TablixHierarchyType() { Items = new object[] { CreateTablixRowMembers() } };
        }

        private TablixMembersType CreateTablixRowMembers()
        {
            TablixMembersType tablixMembers = new TablixMembersType();
            tablixMembers.TablixMember = new TablixMemberType[]
            {
                CreateTablixRowMember0(),
                CreateTablixRowMember1(),
            };
            return tablixMembers;
        }

        private TablixMemberType CreateTablixRowMember0()
        {
            TablixMemberType tmt = new TablixMemberType();

            tmt.Items = new object[]
            {
                CreateTablixRowMemberKeepWithGroup(),
                true,
            };
            tmt.ItemsElementName = new ItemsChoiceType72[]
            {
                ItemsChoiceType72.KeepWithGroup,
                ItemsChoiceType72.RepeatOnNewPage,
            };

            return tmt;
        }

        private TablixMemberTypeKeepWithGroup CreateTablixRowMemberKeepWithGroup()
        {
            return TablixMemberTypeKeepWithGroup.After;
        }

        private TablixMemberType CreateTablixRowMember1()
        {
            TablixMemberType tmt = new TablixMemberType();
            tmt.Items = new object[] { CreateTablixRowMemberGroup() };
            tmt.ItemsElementName = new ItemsChoiceType72[] { ItemsChoiceType72.Group };
            return tmt;
        }

        private GroupType CreateTablixRowMemberGroup()
        {
            return new GroupType() { Name = "详细信息" };
        }

        /// <summary>
        /// ReportDataSource.Name和RDLC文件的DataSetNamey应保持一致
        /// 对于DataGrid构造的报表,可统一固定用"CustormerDataSet";
        /// DataSetName不需要作为参数传进来
        /// </summary>
        /// <returns>DataSet Name</returns>
        private string CreateDataSetName()
        {
            return String.IsNullOrEmpty(DataSetName) ? "CustomerDataSet" : DataSetName;
        }

        private StyleType CreateTablixStyle()
        {
            StyleType st = new StyleType();
            st.Items = new object[] { CreateTablixBorder() };
            st.ItemsElementName = new ItemsChoiceType4[] { ItemsChoiceType4.Border };
            return st;
        }

        // Tablix的外边框格式
        private BorderType CreateTablixBorder()
        {
            BorderType bt = new BorderType();

            bt.Items = new object[] 
            {
                "Black",
                "Solid",
                "2pt"
            };
            bt.ItemsElementName = new ItemsChoiceType2[] 
            { 
                ItemsChoiceType2.Color,
                ItemsChoiceType2.Style,
                ItemsChoiceType2.Width
            };

            return bt;
        }

        #endregion
    }

TablixRdlcGenerator.cscs

 

第三步:提取DataGrid的数据

一、重要从DataGrid提取各种Column的Width、BindingPath、Header的Content和各种单元格的数额。数据填充DataTable的Rows,
Binding帕特h填充DataTable的Columns,

Header的Content用来作为报表Tablix的标题行。BindingPath,对于DataTemplate和DataGridHyperlinkColumn不清楚咋个取提取数据.

 

2、dataGrid.ScrollIntoView(dataGrid.Items[rowIndex])这些是至关重要。DataGrid用了3个虚构啥子来着的(名字不重大,原理轻松,计算机世界大量管理品质的都是用那些方法),正是复用分界面显示,2个窗口里能装下的几10条RowContainer,每便滚动,人要见到的时候才重新提取新的要突显的多寡。

这么提取数万条记下时,分界面不会卡,也不会占用许多内存,每一回是要来得的时候才取几10条,一小点取。要用,才给,只给要求的这一点。

美高梅开户网址 31美高梅开户网址 32

      /// <summary>
        /// DataGrid的转换器,从DataGrid里提取出数据源,以及HeaderName、Binding的Path和ActualWidth
        /// </summary>
        /// <param name="dataGrid">包含数据的DatGrid</param>
        /// <param name="dt">DataGrid数据源转换成的DataTable</param>
        /// <param name="headerNames">DataGridColumn.Header</param>
        /// <param name="bindingPaths"> DataGridBoundColumn.Binding.Path</param>
        public static void DataGridAdapter(this DataGrid dataGrid, DataTable dt, List<string> headerNames, List<string> bindingPaths, List<double> widths)
        {
            // 取出DataGridColumn的Header,BingdingPath,ActualWidth为构造rdlc文件准备数据
            headerNames.Clear();
            bindingPaths.Clear();
            widths.Clear();
            for (int index = 0; index < dataGrid.Columns.Count; index++)
            {
                headerNames.Add(dataGrid.Columns[index].Header as string);
                widths.Add(dataGrid.Columns[index].ActualWidth);
                //string tempBindingPath = ((dataGrid.Columns[index] as DataGridBoundColumn).Binding as Binding).Path.Path;
                string tempBindingPath = GetDataGridColumnBindingPath(dataGrid.Columns[index]);
                bindingPaths.Add(tempBindingPath);

                if (String.IsNullOrEmpty(tempBindingPath) == false)
                    dt.Columns.Add(tempBindingPath, typeof(string));
            }

            for (int rowIndex = 0; rowIndex < dataGrid.Items.Count; rowIndex++)
            {
                // 要显示后,才能取到数据
                DataGridRow rowContainer = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromIndex(rowIndex);
                // 因为Peformance问题,EnableRowVirtualization被设置为true,只加载要显示的数据
                // 重新滚动,然后再重用这些DataGridRow
                if (rowContainer == null)
                {
                    dataGrid.UpdateLayout();
                    dataGrid.ScrollIntoView(dataGrid.Items[rowIndex]);
                    rowContainer = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromIndex(rowIndex);
                }
                if (rowContainer != null)
                {
                    DataGridCellsPresenter presenter = DataGridHelper.GetVisualChild<DataGridCellsPresenter>(rowContainer);
                    if (presenter != null)
                    {
                        DataRow dr = dt.NewRow();
                        bool isLastRowAllEmpty = true;
                        for (int columnIndex = 0; columnIndex < bindingPaths.Count; columnIndex++)
                        {
                            DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(columnIndex);                           
                            if (cell != null)
                            {
                                if (cell.Content is TextBlock)
                                {
                                    //TODO: DataGridHyperlinkColumn取不到数据
                                    dr[bindingPaths[columnIndex]] = (cell.Content as TextBlock).Text;
                                    if (!String.IsNullOrEmpty((cell.Content as TextBlock).Text)) isLastRowAllEmpty = false;
                                }
                                else if (cell.Content is CheckBox)
                                {
                                    string value = ((cell.Content as CheckBox).IsChecked == true) ? "是" : "否";
                                    dr[bindingPaths[columnIndex]] = value;
                                }
                                else if (cell.Content is ComboBox)
                                {
                                    dr[bindingPaths[columnIndex]] = (cell.Content as ComboBox).Text;
                                    if (!String.IsNullOrEmpty((cell.Content as ComboBox).Text)) isLastRowAllEmpty = false;
                                }
                            }
                        }

                        if (dataGrid.CanUserAddRows && (rowIndex == dataGrid.Items.Count - 1))
                        {
                            // 如果CanUserAddRows被设置为true,只有最后一行的数据都不为空(CheckBox不算作内),才把数据添加到DataTable
                            if (isLastRowAllEmpty)
                            {
                                continue;
                            }
                        }
                        dt.Rows.Add(dr);
                    }
                }
            }
        }

提取DataGrid数据

 

第5步:填充数据

首要在安装ReportViewer类的LocalReport.ReportPath
和LocalReport.DataSources那两项。

美高梅开户网址 33美高梅开户网址 34

        /// <summary>
        ///  报表数据源发生变化时,及时更新显示报表控件的数据源
        /// </summary>
        /// <param name="reportDataModel">报表数据模型基类</param>
        public void ResetReportData(ReportDataModel reportDataModel)
        {
            if (reportDataModel != null)
            {
                reportViewer.Reset();
                reportViewer.LocalReport.DataSources.Clear();
                reportViewer.Clear();

                if (!reportDataModel.IsDataGrid)
                    reportViewer.LocalReport.ReportPath = reportDataModel.RDLCReportPath;
                else
                {
                    // 如果是DataGrid转换成的,直接从内存流里加载数据
                    if (reportDataModel.MsDataGrid != null)
                    {
                        reportViewer.LocalReport.LoadReportDefinition(reportDataModel.MsDataGrid);
                        // 用完就释放掉,流所占用的所有资源
                       // reportDataModel.MsDataGrid.Dispose();
                    }
                }
                reportViewer.LocalReport.DataSources.Add(reportDataModel.ReportDataSource);
                reportViewer.RefreshReport();
            }
        }

ResetReportData

 

第6步:提供一个ReportHelper类

具体拼接数据以及总括中度等,还有用另1套办法得以达成第二个效能。

1、依照DataGrid每列的幅度,按百分比,重新恢复设置每列的肥瘦。

美高梅开户网址 35美高梅开户网址 36

 1         /// <summary>
 2         /// 根据DataGrid的Column的Actual Width来设置报表里对应Tablix的TablixColumn的宽度
 3         /// </summary>
 4         /// <param name="reportWidth">报表的总宽度</param>
 5         /// <param name="widths">DataGrid的Column的Actual Width</param>
 6         /// <param name="tablixColumnWidths">重新按百分比计算的TablixColumn的宽度列表</param>
 7         public static void CalcTablixColumnWidth(string reportWidth, List<double> widths, out List<string> tablixColumnWidths)
 8         {
 9             double totalWidth = 0.0;
10             double originalTotalWidth = 0.0;
11             List<double> rateColumnWidth = new List<double>();
12             string unit = reportWidth.Substring(reportWidth.Length - 2, 2);
13 
14             // 取到报表宽度字符串除去单位in或者cm的数值
15             Double.TryParse(reportWidth.Substring(0, reportWidth.Length - 2), out totalWidth);
16 
17 
18             for (int index = 0; index < widths.Count; index++)
19                 originalTotalWidth += widths[index];
20 
21 
22             for (int index = 0; index < widths.Count; index++)
23                 rateColumnWidth.Add(widths[index] / originalTotalWidth);
24 
25             tablixColumnWidths = new List<string>();
26             tablixColumnWidths.Clear();
27             for (int index = 0; index < widths.Count; index++)
28                 tablixColumnWidths.Add((rateColumnWidth[index] * totalWidth).ToString() + unit);
29         }

CalcTablixColumnWidth

贰、把内部存款和储蓄器中的流读出来,生成对应的路虎极光DLC文件,作者那里没调用。所以设置LocalReport.ReportPath换到reportViewer.LocalReport.LoadReportDefinition(reportDataModel.MsDataGrid);

美高梅开户网址 37美高梅开户网址 38

 1         /// <summary>
 2         /// 把内存的流生成为rdlc文件
 3         /// </summary>
 4         /// <param name="rdlc">按rdlc格式构造成功的内存流</param>
 5         public static void DumpRdlc(MemoryStream rdlc)
 6         {
 7             string tempRdlcPath = AppDomain.CurrentDomain.BaseDirectory + @"../../../CommonReport/Templates/GeneratedDataGrid.rdlc";
 8             if (File.Exists(tempRdlcPath))
 9                 File.Delete(tempRdlcPath);
10 
11             using (FileStream fs = new FileStream(tempRdlcPath, FileMode.Create))
12             {
13                 rdlc.WriteTo(fs);
14             }
15         }

DumpRdlc

叁、部分调用的代码——给一个简易的途观DLC模板,以提供表头的书体格式和表内部数据等体制相关的消息,然后再用DataGrid里提取的多寡,填充到报表里

美高梅开户网址 39美高梅开户网址 40

 1         /// <summary>
 2         /// 将DataGrid的数据抽取出来,转换成rdlc报表,以实现对提供DataGrid的打印、预览、分页和页面布局等功能的支持
 3         /// 但需要提供一个rdlc报表的模板,必须包括页眉页脚,至少一列数据和标题,以便拿到数据的表头的
 4         /// style和数据项的style,这一列数据项必须是第一项(且第一项的表头和数据都完整提供了style)
 5         /// </summary>
 6         /// <param name="dataGrid">提供数据的DataGrid</param>
 7         /// <param name="reportViewer">要加载DataGrid数据的ReportViewer</param>
 8         /// <param name="rdlcModelFileName">rdlc模板的完整路径</param>
 9         /// <param name="headline">报表标题</param>
10         public static void Print(this DataGrid dataGrid, CommonReport.Views.ReportViewer reportViewer, string rdlcModelFileName, string headline)
11         {
12             if (!File.Exists(rdlcModelFileName)) return;
13 
14             // 从DataGrid对应的rdlc模板里读出报表数据来
15             Report report = null;
16             string dataSourceName = DatasetName;
17             dataGrid.UnderRdlcGenProc(reportViewer, headline, gen =>
18             {
19                 report = gen.Read(rdlcModelFileName);
20 
21                 // ReportDataSource的Name应该用取DataSet的Name
22                 #region 取DataSourceName
23 
24                 DataGridHelper.ResetRdlcHeadline(report, headline);
25                 for (int index = 0; index < report.Items.Length; index++)
26                 {
27                     if (report.Items[index] is DataSetsType)
28                     {
29                         DataSetsType dataSets = report.Items[index] as DataSetsType;
30                         dataSourceName = dataSets.DataSet[0].Name;
31                         break;
32                     }
33                 }
34 
35                 #endregion
36             }, (gen, ms, dt) =>
37             {
38                 // 根据从DataGrid里提取的数据重新构造rdlc文件
39                 RdlcReportAdapter(report, gen.HeaderNames, gen.FieldNames, gen.Widths);
40                 gen.Write(ms, report);
41                 return new Microsoft.Reporting.WinForms.ReportDataSource(dataSourceName) { Value = dt };
42             });
43         }

Print

四、打字与印刷的有关页面的有个别私下认可设置(看事态)

美高梅开户网址 41美高梅开户网址 42

1             // 设置默认打印布局模式为“显示物理页”
2             reportViewer.SetDisplayMode(DisplayMode.PrintLayout);
3             reportViewer.ZoomMode = ZoomMode.Percent;
4             reportViewer.ZoomPercent = 100;

打字与印刷设置

伍、TreeView反射那块——功效3

美高梅开户网址 43美高梅开户网址 44

 1         /// <summary>
 2         /// TreeView上选择的项发生变化时,根据所选TreeViewItem的Header信息和Tag里所存储的信息,利用反射构造对应报表的数据类实例
 3         /// 加载报表模板,调用委托将数据传到报表的显示控件上
 4         /// </summary>
 5         /// <param name="sender"></param>
 6         /// <param name="e"></param>
 7         private void RdlcTree_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
 8         {
 9             if ((sender != null) && (sender is TreeView))
10             {
11                 if ((sender as TreeView).SelectedItem is TreeViewItem)
12                 {
13                     TreeViewItem tempItem = (sender as TreeView).SelectedItem as TreeViewItem;
14                     if (tempItem.Tag is TreeViewItemDataType)
15                     {
16                         TreeViewItemDataType tempTreeViewDataType = tempItem.Tag as TreeViewItemDataType;
17                         // 报表类型
18                         if (tempTreeViewDataType.UserControlType == TreeViewItemDataType.ControlType.Report)
19                         {
20                             string reportDataModelInstanceName = tempItem.Header + "Model";
21                             Type type = typeof(ReportDataModel);
22                             Assembly assembly = type.Assembly;
23                             try
24                             {
25                                 ReportDataModel reportDataModelInstance = (ReportDataModel)assembly.CreateInstance(type.Namespace + "." + reportDataModelInstanceName);
26                                 if (reportDataModelInstance != null)
27                                 {
28                                     reportDataModelInstance.RDLCReportPath = (tempItem.Tag as TreeViewItemDataType).FullPath;
29                                     reportDataModelInstance.InitDataSource();
30                                     if (Viewer != null) 
31                                         Viewer.ResetReportData(reportDataModelInstance);
32                                 }
33                             }
34                             catch (Exception ex)
35                             {
36                                 MessageBox.Show(ex.Message);
37                             }
38                         }
39 
40                         // DataGrid 类型
41                         else if (tempTreeViewDataType.UserControlType == TreeViewItemDataType.ControlType.DataGrid)
42                         {
43                             Type type = this.GetType();
44                             Assembly assembly = type.Assembly;
45                             try
46                             {
47                                 UserControl dataGridUserControlInstance = (UserControl)assembly.CreateInstance(type.Namespace + ".DataGrid." + tempItem.Header);
48                             }
49                             catch (Exception ex)
50                             {
51                                 MessageBox.Show(ex.Message);
52                             }
53                         }
54                     }
55                 }
56             }
57         }

RdlcTree_SelectedItemChanged

6、通过VisualTreeHelper找到钦点项目标子也许父的主意,可在WPF里通用

美高梅开户网址 45美高梅开户网址 46

        /// <summary>
        /// 找出子Visual的特定类型的Parent
        /// </summary>
        /// <typeparam name="T">指定类型</typeparam>
        /// <param name="child">继承自Visual的基本控件类型的子Visual</param>
        /// <returns></returns>
        public static T GetParent<T>(Visual child) where T : Visual
        {
            T parent = default(T);
            Visual visual = VisualTreeHelper.GetParent(child) as Visual;
            parent = visual as T;
            if (parent == null)
                return GetParent<T>(visual);
            else
                return parent;
        }

        /// <summary>
        /// 遍历取父控件的子Viusal,取到指定类型的子Viusal
        /// </summary>
        /// <typeparam name="T">T是Visual或其子类(基本上WPF的控件都是Visual的子类),指定子类型</typeparam>
        /// <param name="parent">父控件</param>
        /// <returns>子Viusal</returns>
        public static T GetVisualChild<T>(Visual parent) where T : Visual
        {
            T child = default(T);
            int numVisuals = VisualTreeHelper.GetChildrenCount(parent);

            for (int i = 0; i < numVisuals; i++)
            {
                Visual visual = (Visual)VisualTreeHelper.GetChild(parent, i);
                child = visual as T;
                if (child == null)
                    child = GetVisualChild<T>(visual);
                else
                    break;
            }
            return child;
        }

VisualTreeHelper

柒、提供一个数额深拷贝的通用方法(C#类以及除基类型之外,许多都以传引用,那一个是地点,值拷贝倒霉搞,这一个方法直接拷贝流,不过必须类的每一种字段都援助连串化)

美高梅开户网址 47美高梅开户网址 48

 1         /// <summary>
 2         /// 对引用类型的数据——“所有字段都加了Serializable特性,以支持序列化”
 3         /// 利用序列化和反序列化实现深度拷贝,即拷贝了堆上的数据,搞了个堆的副本
 4         /// 而不是浅拷贝那样,只是拷贝了一个指向数据堆的内存地址
 5         /// 非常实用的小函数,支持所有引用类型数据
 6         /// </summary>
 7         /// <param name="original">要拷贝的引用类型数据源</param>
 8         /// <returns>源数据的副本</returns>
 9         public static object DeepColne(Object original)
10         {
11             // 构造一个临时的内存流
12             using (MemoryStream ms = new MemoryStream())
13             {
14                 // 调用BinaryFormatter来完成复杂的序列化和反序列化工作
15                 BinaryFormatter formatter = new BinaryFormatter();
16 
17                 // StreamingContext—描述给定的序列化流的源和目标,并提供一个由调用方定义的附加上下文
18                 formatter.Context = new StreamingContext(StreamingContextStates.Clone);
19 
20                 // 把对象图序列化到内存流,original的每个字段必须标记为可序列化,否则会出错
21                 formatter.Serialize(ms, original);
22 
23                 // 反序列化之前需要设置流的当前位置为最开始的位置
24                 ms.Position = 0;
25 
26                 // 把内存流反序列化为对象图,再以基类的形式返回给调用者
27                 return formatter.Deserialize(ms);
28             }
29         }

DeepColne

 

6、运营效果

一、含有DataGrid可能别的控件的分界面

美高梅开户网址 49

二、点击打字与印刷后,报表生成

美高梅开户网址 50

附:

1、ReportItems!具体普拉多DLC报表上控件的名称.Value那些取到报表设计器里肆意项的数量,然后就可在表明式里进行各个逻辑运算。比方:

= ReportItems!forestryMaintenance.Value + ReportItems!pension.Value +
ReportItems!SumPolicy.Value

  • ReportItems!livingExpenses.Value + ReportItems!resettlement.Value

2、合并单元格,纵向和横向的

以此要分组,具体请找出英特网能源

3、调控每页都显得

对此题目,设置KeepWith属性和Tablix一齐现身就好;还有三个主意,是设置任何的质量,目前忘了,互连网有

肆、XML很注重,据近来所知,微软的工程文件、WPF、打字与印刷、报表、XPS、Office200柒自此版本等,XML都是基本。(未完,待续)

五、页面纸张尺寸(PageSetting里的壹部分有关大小的值,单位都以百分之十0
inch;页面设置布局排版打字与印刷有点麻烦,稍不在意就多出去一点,字体、页眉、页脚、边框、页边距等),如下图:

美高梅开户网址 51

 6、border style

美高梅开户网址 52

 

最后,必须感激和致意蜡人张前辈:

2.微软GotReportViewer官方的案例:

(约有20来个,很详细。有时候会上穿梭)

发表评论

电子邮件地址不会被公开。 必填项已用*标注

网站地图xml地图