gridview導出到excel

gridview導出到excel有很多方法,這裏列出兩種,其中第一種是導出,第二種應該叫寫入。在此推薦第二種方法。貼代碼 :
第一種,在按鈕單擊事件裏寫:
       //首先清除分頁      
       GridView1.AllowPaging = false;
        GridView1.DataBind();
        Response.Clear();
        Response.Buffer = true;
        //設定輸出的字符集
        Response.Charset = "GB2312";
        //解決導出亂碼問題
        Response.Write("<meta http-equiv=Content-Type content=text/html;charset=GB2312>");
 
        //假定導出的文件名爲test.xls
        Response.AppendHeader("Content-Disposition", "p_w_upload;filename=test.xls" .ToString());
        //解決導出亂碼問題
        Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
 
        //設置導出文件的格式
        Response.ContentType = "application/ms-excel";
        //關閉ViewState
        this.EnableViewState = false;
        StringWriter stringWriter = new StringWriter();
        HtmlTextWriter textWriter = new HtmlTextWriter(stringWriter);
        GridView1.RenderControl(textWriter);
        //把HTML寫回瀏覽器
        Response.Write(stringWriter.ToString());
        Response.Flush();
        Response.End();
        GridView1.AllowPaging = true;//恢復分頁
        //爲GridView重新綁定數據源
        GridView1.DataBind(); ;
}
另外,要在下面再加上一段代碼:
public override void VerifyRenderingInServerForm(Control control)
    {
       
    }
這種方式其實並不是真正的導出了excel,用記事本打開該文件,你會發現它是html代碼。如果只是簡單的把數據導出來,倒是可以考慮。
第二種,是把gridview的每個單元格的內容讀出來然後寫入到excel對應的單元格里。
 if (GridView1.Rows.Count == 0)
            return;
        Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
        excel.Application.Workbooks.Add(true);
        excel.Visible = true;
        for (int j = 0; j < GridView1.Columns.Count; j++) {
            excel.Cells[1, j + 1] = GridView1.Columns[j].HeaderText;
        }
            for (int j = 0; j < GridView1.Rows.Count; j++)
            {
                for (int k = 0; k < GridView1.Columns.Count; k++)
                {
                    excel.Cells[j + 2, k + 1] = GridView1.Rows[j].Cells[k].Text;
                }
           }
這種方法要注意的是,首先應該引用Microsoft.office.interop.excel 11.0.0.0;
另外,如果前臺gridview是自動生成字段,那麼gridview.columns是獲取不到值的,爲0。
還有,excel單元格 Cells[]中的索引,它是從1開始的,和gridview從0開始不一樣。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章