The GridView data export to Excel

The GridView data export to Excel

About the problem of maintaining the original style. The approach here is to say very specific to each add style and then later there is no longer deal with this problem.

e.Item.Cells[0].Attributes.Add("style","vnd.ms-excel.numberformat:@"); 

I did not even try this, do not know if this is like using a ~

I just need to keep every style columns when rowdatabound plus a e.Row.Cells [3] .Attributes.Add ( "class ", "text");
then Response after grd.RenderControl (hw) .Write (style) test was about ~ da ~ ^^ this is easy

Oh, yes, string style = @ "<style> .text {mso-number-format: \ @;} </ style>"; 

 

If there gridview page, but also before adding <- - [endif]!>:
  This.GridView1.AllowPaging = to false;
  this.GridView1.DataBind ();

After the re-paging is set to true, re-tied it on ok ~

 

VerifyRenderingInServerForm must reload .... - = empty function body can ....

 

Call may also occur during the execution of Render () in <-! [Endif] -> RegisterForEventValidation error. You need to add red part on the page

<!--[endif]-->

<%@ Page Language="C#" EnableEventValidation = "false" AutoEventWireup="true"

 CodeFile=".....aspx.cs" Inherits="...." %>

 

 About those special controls are exported ..... online a written DisableControls function, with the cycle method replaces linkbutton into literal and dropdownlist control

 As mentioned earlier, I had a debug step by step, although seemingly is linkbutton execution remove out of the cell, but finally exported excel still hate hyperlinks, did not try to remove a lot of times .... orz will not work, do not know because I have a problem js before the time of rowdatabound tied it ... but that can not afford to go .... how ah ....... (┬_┬)

Finally, depressed ~ only to this appearance. . . orz

 

All online sensation common problems encountered ............ even have this RP ah ~ - =

 

===========================================================

  http://www.cnblogs.com/badwood316/archive/2008/01/24/1051344.html  

 1        private void DumpExcel(GridView gv, string FileName)
 2        {//带格式导出
 3            string style = @"<style> .text {  } </script>";
 4            Response.ClearContent();
 5            Response.Charset = "GB2312";
 6            Response.ContentEncoding = System.Text.Encoding.UTF8;
 7            Response.AddHeader("content-disposition", "attachment; filename=" + HttpUtility.UrlEncode(FileName, Encoding.UTF8).ToString());
 8            Response.ContentType = "application/excel";
 9            StringWriter sw = new StringWriter();
10            HtmlTextWriter htw = new HtmlTextWriter(sw);
11            gv.RenderControl(htw);
12            // Style is added dynamically
13            Response.Write(style);
14            Response.Write(sw.ToString());
15            Response.End();
16        }
17        public override void VerifyRenderingInServerForm(Control control)
18        {
19        }
20

        The above line 17 overloaded function is necessary, otherwise it will report "GridView to have run = server in the From in vivo" wrong.
        In addition, the role of the control variable style GridView column style, to avoid excel table for the character as a leading digital 0 is truncated to this problem, a method by adding it to Response.Write output stream. Finally add style to the ID column. This step needs to be done in RowDataBound event:

1protected void gvUsers_RowDataBound(object sender, GridViewRowEventArgs e)
2
3if (e.Row.RowType == DataControlRowType.DataRow)
4{
5e.Row.Cells[1].Attributes.Add("class", "text"); 
6}
7}

 

 

=============================================================

 http://www.cnblogs.com/allancandy/archive/2008/01/23/1050559.html

DisableControls function, the method using the circulating linkbutton replaced literal and control dropdownlist

private void DisableControls(Control gv)

{

LinkButton lb = new LinkButton();

Literal l = new Literal();

string name = String.Empty;

for (int i = 0; i < gv.Controls.Count; i++)

{

if (gv.Controls[i].GetType() == typeof(LinkButton))

{

l.Text = (gv.Controls[i] as LinkButton).Text;

gv.Controls.Remove(gv.Controls[i]);

gv.Controls.AddAt (i, l);

}

else if (gv.Controls[i].GetType() == typeof(DropDownList))

{

l.Text = (gv.Controls[i] as DropDownList).SelectedItem.Text;

gv.Controls.Remove(gv.Controls[i]);

gv.Controls.AddAt (i, l);

}

if (gv.Controls[i].HasControls())

{

DisableControls(gv.Controls[i]);

}

}

}

The method is very simple, just replace linkbuton and dropdownlist into a literal control, and select the text item attribute assigned to the literal control. The method needs to be called before exporting

 

 

=============================================================

 

GridView export Excel method
a, as a namespace references
the using the System.IO;
the using the System.Text;
Second, detailed code

Method One: write code directly in the page


    /// <summary>
    /// 数据导出
    /// </summary>
    /// <param name="FileType"></param>
    /// <param name="FileName"></param>
    private void Export(string FileType, string FileName)
    {
        Response.Charset = "GB2312";
        Response.ContentEncoding = System.Text.Encoding.UTF8;//注意编码
        Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, Encoding.UTF8).ToString());
        Response.ContentType = FileType;
        this.EnableViewState = false;
        StringWriter tw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(tw);
        gridGatewayDetails.RenderControl (hw);
        Response.Write(tw.ToString());
        Response.End();
    }

The second method to improve the above code public methods:


    /// <Summary>
    /// export grid data to Excel
    /// </ Summary>
    /// <param name = "Ctrl"> grid name (e.g. GridView1, and) </ param>
    /// <param name = file type "FileType"> to export (Excel: the Application / MS-Excel) </ param>
    /// <param name = "fileName"> to save the file name </ param>
    public static void GridViewToExcel (Control Ctrl, the FileType String, String FileName)
    {
        HttpContext.Current.Response.Charset = "GB2312";
        HttpContext.Current.Response.ContentEncoding = Encoding.UTF8; // Note coding
        HttpContext.Current.Response.AppendHeader ( "Content-Disposition" ,
            "Attachment; filename =" + HttpUtility.UrlEncode (fileName, Encoding.UTF8) .ToString ());
        HttpContext.Current.Response.ContentType = FileType;//image/JPEG;text/HTML;image/GIF;vnd.ms-excel/msword
        ctrl.Page.EnableViewState = false;
        StringWriter tw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(tw);
        ctrl.RenderControl(hw);
        HttpContext.Current.Response.Write(tw.ToString());
        HttpContext.Current.Response.End();
    }

Third, pay attention:

When exported, if a field is long numbers (such as identity card number 511922198507151512), numbers beginning with 0 data and the like (eg 0809111212). If not addressed in an Excel file will be exported separately and as 5.11922E + 17 809 111 212 to deal with, so inconsistent and we want to achieve practical results. So we have to be addressed, namely the prescribed format to the cell data. Common format is as follows:

1) Text: vnd.ms-excel.numberformat: @
2) Date: vnd.ms-excel.numberformat: YYYY / mm / dd
. 3) numbers: vnd.ms-excel.numberformat: #, ## 0.00
. 4) Currency : vnd.ms-excel.numberformat: ¥ #, ## 0.00
5) percentage: vnd.ms-excel.numberformat: # 0.00%

Use as follows:

// to the first format to a cell

e.Item.Cells[0].Attributes.Add("style","vnd.ms-excel.numberformat:@");

// set to the fourth cell format
e.Item.Cells [3] .Attributes.Add ( "style ", "vnd.ms-excel.numberformat:. ¥ #, ### 00");

Reproduced in: https: //www.cnblogs.com/baishiying/archive/2012/10/16/2726019.html

Guess you like

Origin blog.csdn.net/weixin_34179968/article/details/93440083