GridView exports Excel implementation principles and code

  • 2020-05-19 04:39:32
  • OfStack

In order to complete the tasks assigned by the leader, I have been doing data presentation these days. Due to the tight schedule, I haven't done too complicated data presentation. GridView was used to display the database tables. Little is done with the GridView format. SQL is loaded from the configuration file, and the data is bound directly to GridView. Found 1 some problems, such as automatic binding GridView column width is not set, while GridView form output is not belt width information, so lead to more table columns will show up when squeezed into the page is very ugly, due to the column number of the table is not fixed, so can't simple with a template column way, finally had to set the table width directly into a big number.

In addition, a function of exporting Excel was made. The main code is as follows:

 
private void DumpExcel(GridView gv, string FileName) 
{// Formatted export  
string style = @"<style> .text { mso-number-format:\@; } </style>"; 
Response.ClearContent(); 
Response.Charset = "GB2312"; 
Response.ContentEncoding = System.Text.Encoding.UTF8; 
Response.AddHeader("content-disposition", "attachment; filename=" + HttpUtility.UrlEncode(FileName, Encoding.UTF8).ToString()); 
Response.ContentType = "application/excel"; 
StringWriter sw = new StringWriter(); 
HtmlTextWriter htw = new HtmlTextWriter(sw); 
gv.RenderControl(htw); 
// Style is added dynamically 
Response.Write(style); 
Response.Write(sw.ToString()); 
Response.End(); 
} 
public override void VerifyRenderingInServerForm(Control control) 
{ 
} 

The overloading function on line 17 above is required, otherwise the error "GridView must be in From with run=server" will be reported.
In addition, the function of the variable style is to control the style of the GridView column, to avoid the problem of the character leading 0 being truncated as a number in the excel table, and to add it to the output stream through the Response.Write method. Finally, add the style to the ID column. This step needs to be completed in the RowDataBound event:
 
1protected void gvUsers_RowDataBound(object sender, GridViewRowEventArgs e) 
{ 
if (e.Row.RowType == DataControlRowType.DataRow) 
{ 
e.Row.Cells[1].Attributes.Add("class", "text"); 
} 
} 

Related articles: