GridView数据导入Excel/Excel数据读入GridView
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 }
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 }
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 }
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 }