Npoi export WPF DataGrid control display data

Source: Internet
Author: User
Tags wpf datagrid

Recently do a project, need to export DataGrid display data, in the middle encountered a lot of pits, in this record, convenient to view later, but also hope to be able to use the people, a little help.

Exporting the data displayed by the DataGrid is not the ItemsSource of the DataGrid, which is distinguished by the fact that the display data for the DataGrid is exported, which is what you see and what you get.

As an example:

I have a people entity class, which contains 6 fields, as follows

 Public classpeople{ Public stringName {Get;Set; }  Public intAge {Get;Set; }  Public intSex {Get;Set; }  Public stringClassName {Get;Set; }  Public stringGradename {Get;Set; }  Public stringSchoolname {Get;Set; }}

However, the collection of list<people> is assigned to the ItemsSource of the DataGrid, but my page shows 5 fields and even a converter's use

<DataGridx:name= "Dg_x"canuseraddrows= "False"AutoGenerateColumns= "False">  <Datagrid.columns>    <DatagridtextcolumnHeader= "Name"Binding="{Binding Name}"Width="*" />    <DatagridtextcolumnHeader= "Age"Binding="{Binding Age}"Width="*" />    <DatagridtextcolumnHeader= "Gender"Binding="{Binding Sex,converter={staticresource Sexcov}}"Width="*" />    <DatagridtextcolumnHeader= "Grade"Binding="{Binding Gradename}"Width="*" />    <DatagridtextcolumnHeader= "School"Binding="{Binding Schoolname}"Width="*" />  </Datagrid.columns></DataGrid>

The result of the export is the data displayed on the DataGrid, with a little bit of style added

Next, let's introduce the two pits I encountered while writing the code.

First, the Code order problem

Do the above content roughly need to do two work, the first is to get to the cell value of the DataGrid, basically Baidu a bit, will see a method, a lot of blogs have, as follows

Http://www.cnblogs.com/qq247039968/p/4066058.html

This method itself is not a problem, but when the DataGrid has a scrollbar, that is, the DataGrid row is not fully rendered when the situation is problematic.

Suppose, I now have 30 data, but I have not dragged the scroll bar, the direct point of the export, will throw the following exception:

Looked at the code, because presenter this is null, continue to break the point trace, found here Numvisuals get the value is 0, not 1, that is, not get the content, so return null.

The reason for the above problem is that the following code is a sequential issue

We all know that the updatelayout function is the meaning of the update layout, the two code is to update the layout, and then scroll to the location of rowindex, so, still no rendering success.

The correct way of writing is to change the order of the two sentences, first scroll, then update, there will be no problem.

 Public Static classdatagridplus{/// <summary>    ///get row of DataGrid/// </summary>    /// <param name= "DataGrid" >DataGrid Control</param>    /// <param name= "RowIndex" >DataGrid Row Number</param>    /// <returns>the specified line number</returns>     Public StaticDataGridRow GetRow ( ThisDataGrid DataGrid,intRowIndex) {DataGridRow Rowcontainer=(DataGridRow) DataGrid.ItemContainerGenerator.ContainerFromIndex (RowIndex); if(Rowcontainer = =NULL) {Datagrid.scrollintoview (Datagrid.items[rowindex]);            Datagrid.updatelayout (); Rowcontainer=(DataGridRow) DataGrid.ItemContainerGenerator.ContainerFromIndex (RowIndex); }        returnRowcontainer; }    /// <summary>    ///gets a child visual of the first specified type in the parent visual object/// </summary>    /// <typeparam name= "T" >visual Object Type</typeparam>    /// <param name= "parent" >Parent Visual Object</param>    /// <returns>the first child visual object of the specified type</returns>     Public StaticT getvisualchild<t> (Visual parent)wheret:visual {T child=default(T); intNumvisuals =Visualtreehelper.getchildrencount (parent);  for(inti =0; i < numvisuals; i++) {Visual v=(Visual) visualtreehelper.getchild (parent, I); Child= V asT; if(Child = =NULL) { child= getvisualchild<t>(v); }            if(Child! =NULL)            {                 Break; }        }        returnChild ; }    /// <summary>    ///get the DataGrid control cell/// </summary>    /// <param name= "DataGrid" >DataGrid Control</param>    /// <param name= "RowIndex" >the line number where the cell is located</param>    /// <param name= "ColumnIndex" >the column number where the cell is located</param>    /// <returns>the specified cell</returns>     Public StaticDataGridCell Getcell ( ThisDataGrid DataGrid,intRowIndex,intcolumnindex) {DataGridRow Rowcontainer=Datagrid.getrow (RowIndex); if(Rowcontainer! =NULL) {Datagridcellspresenter presenter= getvisualchild<datagridcellspresenter>(Rowcontainer); DataGridCell Cell=(DataGridCell) presenter.            Itemcontainergenerator.containerfromindex (columnindex); if(Cell = =NULL) {Datagrid.scrollintoview (Rowcontainer, Datagrid.columns[columnindex]); Cell=(DataGridCell) presenter.            Itemcontainergenerator.containerfromindex (columnindex); }            returncell; }        return NULL; }}
Datagridplus

When you click Export, the scroll bar automatically rolls to the end of the DataGrid

Ii. excessive creation of styles and fonts

The style of npoi is for cells, so if you export the most common table, you need at least 9 styles, this is not the font or what, but the border

Coarse and fine questions, basically a table, the outermost box of the thick line, the interior is a thin wire.

Because, for the first time with Npoi, previously used, so, in the setting style is, to put in the for inside, then the idea is to determine where the column, or where the row, to set the cell style

However, the number of times is not a problem, when the number of more, because of constant new, resulting, will prompt the number of style copied, it seems to have tested 2W data bar.

Therefore, all the styles need to be put forward, at the very beginning of the definition, when needed, the direct assignment is good.

Position, it is defined by enumeration and is easy to use.

 Public enum cellposition{    lefttop,    Top,    righttop, left    ,    Center, right    ,    Leftbottom,    Bottom,    rightbottom,    None}

Also note that Npoi can set the default width by defaultcolumnwidth, but the default height of defaultrowheight and defaultrowheightinpoints settings is not so I think the author in 13, the time has fixed this problem, but do not know why is still not up or down, there is know, hope can leave a message to inform, thank you.

Demo Source

Npoi export WPF DataGrid control display data

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.