用戶控件上的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、瀏覽網頁即可使用