GridView 导入Excel

来源:互联网 发布:电商淘宝是做什么的 编辑:程序博客网 时间:2024/04/30 05:40

 

        <%@ Page EnableEventValidation="false" %>

 

 

 

一、引用如下命名空间
using System.IO;
using System.Text;

 

 

 

Response.ClearContent();

 

Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF8");//防止乱码

 

        string stuname = System.Web.HttpUtility.UrlEncode(this.j.Text.Trim() + "成绩单", System.Text.Encoding.UTF8);

        Response.AddHeader("content-disposition", "attachment; filename=" + stuname + ".xls");

        Response.ContentType = "application/excel";

 

        StringWriter sw = new StringWriter();

        sw.WriteLine("<h2>大学学生成绩表</h2>");

        sw.WriteLine("院系:" + this.yx.Text + "     " + "学制:" + "       " + "入学时间:" + "   " + "学号:" + this.xuehao.Text);

        sw.WriteLine("<br>专业:" + this.zy.Text + "     培养层次:" + this.chenci.Text + "      毕业时间:             姓名:" + this.j.Text);

        HtmlTextWriter htw = new HtmlTextWriter(sw);

        GridView1.RenderControl(htw);

        Response.Write(sw.ToString());

        Response.End();

 

 

    public override void VerifyRenderingInServerForm(Control control)
    {
    }

 

 

 

在导出的时候,如果某个字段为长数字(如身份证号码511922198507151512)、以0开头的编号(如0809111212)之类的数据。如果不加处理在导出的Excel文件中将会被分别当作5.11922E+17和809111212来处理,这样与我们要达到 的实际效果不一致。所以我们要加以处理,即给单元格数据规定格式。常见的格式如下:

1) 文本:vnd.ms-excel.numberformat:@
2) 日期:vnd.ms-excel.numberformat:yyyy/mm/dd
3) 数字:vnd.ms-excel.numberformat:#,##0.00
4) 货币:vnd.ms-excel.numberformat:¥#,##0.00
5) 百分比:vnd.ms-excel.numberformat: #0.00%

使用方法如下:

//给第一个单元格设置格式为

e.Item.Cells[0].Attributes.Add("style","vnd.ms-excel.numberformat:@");

//给第四个单元格设置格式为
e.Item.Cells[3].Attributes.Add("style","vnd.ms-excel.numberformat:¥#,###.00");

 

解决乱码:

 

Response.ContentType = "application/excel";

        Response.Write("<meta http-equiv=Content-Type content=/"text/html; charset=GB2312/">");

 

 

Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");