在Baidu中一找"GridView匯出到Excel"可以很順利的找到我貼到下面的代碼,很多人依照代碼使用,發現以下幾個問題:
(1)StringWriter 不能用,因為沒有引入命名空間System.IO
(2)Encoding不能用,因為沒有引入命名空間System.Text
(3)在使用者控制項上使用的GridView不能重寫VerifyRenderingInServerForm函數。
一、GridView資料匯出到Excel檔案中
1 protected void Button1_Click(object sender, EventArgs e)
2 {
3 Export("application/ms-excel", "自命名檔案名稱.xls");
4 }
5
6 private void Export(string FileType, string FileName)
7 {
8 Response.Charset = "GB2312";
9 Response.ContentEncoding = System.Text.Encoding.UTF7;
10 Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode (FileName, Encoding.UTF8).ToString());
11 Response.ContentType = FileType;
12 this.EnableViewState = false;
13 StringWriter tw = new StringWriter();
14 HtmlTextWriter hw = new HtmlTextWriter(tw);
15 GridView1.RenderControl(hw);
16 Response.Write(tw.ToString());
17 Response.End();
18 }
19 //如果沒有下面方法會報錯類型“GridView”的控制項“GridView1”必須放在具有 runat=server 的表單標記內
20 public override void VerifyRenderingInServerForm(Control control)
21 {
22 }
二、Excel資料匯入到GridView中
1 //讀取Excel資料的代碼:這個很簡單的
2 private DataSet CreateDataSource()
3 {
4 string strCon;
5 strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("excel.xls") + "; Extended Properties=Excel 8.0;";
6 OleDbConnection olecon = new OleDbConnection(strCon);
7 OleDbDataAdapter myda = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", strCon);
8 DataSet myds = new DataSet();
9 myda.Fill(myds);
10 return myds;
11 }
12 protected void Button1_Click(object sender, EventArgs e)
13 {
14 GridView1.DataSource = CreateDataSource();
15 GridView1.DataBind();
16 }
【說明】
1、上面的例子網站上到處都有,我這裡只是貼出來而已;
2、上述例子的代碼是正確的,絕對沒有語法錯誤;
3、但是,上面的代碼只能是針對於GridView控制項直接在aspx頁面上,如果在使用者控制項上使用了GridView控制項,那麼你必須按照以下方式處理了
三、使用者控制項上的GridView如何匯出到Excel表
1、前面步驟跟前面的一樣,你需要一個按鈕來處理匯入/匯出事件
2、你需要把使用者控制項放到某個頁面上,如Test.aspx
3、如果你僅僅這樣,頁面肯定會報錯。
4、為了避免錯誤,你必須在Test.aspx頁面把第一行改成(紅色為添加進去的)
<%@ Page Language="C#" EnableEventValidation = "false" AutoEventWireup="true" CodeFile="SysUser.aspx.cs" Inherits="Autho_SysUser2" %>
5、然後在Test.aspx.cs中重寫
public override void VerifyRenderingInServerForm(Control control)
{
//函數體內沒有任何代碼,切記
}
6、瀏覽網頁即可使用