表格控件(GridView)数据格式化导出到Excel并下载.

来源:互联网 发布:旁氏米粹洗面奶 知乎 编辑:程序博客网 时间:2024/06/04 18:37

将GridView数据按照原有格式导出到Excel表格中便于编辑和打印.

效果如下.

 

 

主要代码

 

 protected void Button2_Click(object sender, EventArgs e)
    
{

        GridView2.Visible 
= true;

        PrepareGridViewForExport(GridView2);
      
//  GridView2.DataBind();
        string attachment = "attachment; filename=download.xls";

        Response.ClearContent();

        Response.AddHeader(
"content-disposition", attachment);

        Response.ContentType 
= "application/ms-excel";

        StringWriter sw 
= new StringWriter();
        HtmlTextWriter htw 
= new HtmlTextWriter(sw);

        GridView2.RenderControl(htw);

        Response.Write(sw.ToString());

        Response.End();
        GridView2.Visible 
= false;
    }

       
public override void VerifyRenderingInServerForm(Control control)
    
{

    }

    
private void PrepareGridViewForExport(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);

            }


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

                l.Text 
= (gv.Controls[i] as CheckBox).Checked ? "True" : "False";

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

                gv.Controls.AddAt(i, l);

            }


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

                PrepareGridViewForExport(gv.Controls[i]);

            }


        }




    }
原创粉丝点击