Gridview導出到EXCEL


為避免出錯的准備

出錯1:類型“GridView”的控件“GridView1”必須放在具有 runat=server 的窗體標記內
解決方案:在后台文件中重載VerifyRenderingInServerForm方法,如:
public override void VerifyRenderingInServerForm(Control control)
{
}

出錯2:只能在執行 Render() 的過程中調用 RegisterForEventValidation(RegisterForEventValidation can only be called during Render();

解決方案:在源中,添加紅色部分<%@ Page Language="C#" EnableEventValidation = "false"CodeFile="ExportGridView.aspx.cs" Inherits="ExportGridView" %>

另外,在使用時,把GRIDVIEW獲取數據的方法getdata()寫成public DataSet  getdata(),return 一個DS,

調用事件里,實例化一個DATASET, 讓它值等於DS,

例:事件{ DataSet  ds = getdata();   
        CreateExcel(ds , "aa.xls");} 或者把數據綁定與獲取DATASET分開

 方法1簡單:

 public void ToExcel()//整個GRIDVIEW導出到EXCEL
    {
        string filename="網銀終端" + DateTime.Now.ToString("yyyyMMdd") + ".xls";
        string style = @"<style> .text { mso-number-format:\@; } </script> "; //解決第一位字符為零時不顯示的問題
       
        this.GridView1.AllowPaging = false;
        this.GridView1.DataBind();

        filename = HttpUtility.UrlEncode(filename, System.Text.Encoding.UTF8);//解決導出EXCEL時亂碼的問題
        Response.ClearContent;
       
        Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
        Response.ContentType = "application/excel";
        Response.AppendHeader("Content-Disposition", "attachment;filename=" + filename);

        System.IO.StringWriter sw = new System.IO.StringWriter();//定義一個字符串寫入對象
        HtmlTextWriter htw = new HtmlTextWriter(sw);//將html寫到服務器控件輸出流
       
        this.GridView1.RenderControl(htw);//將控件GRIDVIEW中的內容輸出到HTW中
        Response.Write(style);
        Response.Write(sw);
        Response.End();

        this.GridView1.AllowPaging = true;
    }

方法2:粘帖直接用

public void CreateExcel(DataSet ds, string FileName)//整個GRIDVIEW導出到EXCEL.xls
    {
        FileName=HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8);//解決導出時文件名漢字顯示亂碼的問題

        HttpResponse resp;
        resp = Page.Response;
        resp.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
        resp.AppendHeader("Content-Disposition", "attachment;filename=" + FileName);
        string colHeaders = "", ls_item = "";

        //定義表對象與行對象,同時用DataSet對其值進行初始化
        DataTable dt = ds.Tables[0];
        DataRow[] myRow = dt.Select();//可以類似dt.Select("id>10")之形式達到數據篩選目的
        int i = 0;
        int cl = dt.Columns.Count;

        //取得數據表各列標題,各標題之間以t分割,最后一個列標題后加回車符
        for (i = 0; i < cl; i++)
        {
            if (i == (cl - 1))//最后一列,加n
            {
                colHeaders += dt.Columns[i].Caption.ToString() + "\n";
            }
            else
            {
                colHeaders += dt.Columns[i].Caption.ToString() + "\t";
            }

        }
        resp.Write(colHeaders);
        //向HTTP輸出流中寫入取得的數據信息

        //逐行處理數據  
        foreach (DataRow row in myRow)
        {
            //當前行數據寫入HTTP輸出流,並且置空ls_item以便下行數據    
            for (i = 0; i < cl; i++)
            {
                if (i == (cl - 1))//最后一列,加n
                {
                    ls_item += row[i].ToString() + "\n";
                }
                else
                {
                    ls_item += row[i].ToString() + "\t";
                }

            }
            resp.Write(ls_item);
            ls_item = "";

        }
        resp.End();
    }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM