.net导出到Excel与Word中(带上下标)

本文介绍了一种简单的方法来将数据从ASP.NET GridView控件导出为Excel和Word文件格式。通过使用C#代码,可以轻松实现数据导出功能,并确保文件名正确编码以避免乱码问题。
//输出到excel的函数,可直接copy到 cs页面
    private void OutExcel(GridView dg, string name)
    
{
        dg.Visible 
= true;
        Response.Clear();
        Response.Buffer 
= true;
        Response.Charset 
= "GB2312";
        name 
= "attachment;filename=" + name;
        Response.AppendHeader(
"Content-Disposition", name);
        Response.ContentEncoding 
= System.Text.Encoding.GetEncoding("GB2312");
        Response.ContentType 
= "application/ms-excel";
        dg.EnableViewState 
= false;
        System.IO.StringWriter oStringWriter 
= new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter oHtmlTextWriter 
= new System.Web.UI.HtmlTextWriter(oStringWriter);
        dg.RenderControl(oHtmlTextWriter);
        Response.Write(oStringWriter.ToString());
        Response.End();
    }

    
//输出到word的函数,可直接copy到 cs页面
    private void OutWord(GridView dg, string name)
    
{
        dg.Visible 
= true;
        Response.Clear();
        Response.Buffer 
= true;
        Response.Charset 
= "GB2312";
        name 
= "attachment;filename=" + name;
        Response.AppendHeader(
"Content-Disposition", name);
        Response.ContentEncoding 
= System.Text.Encoding.GetEncoding("GB2312");
        Response.ContentType 
= "application/ms-word";
        dg.EnableViewState 
= false;
        System.IO.StringWriter oStringWriter 
= new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter oHtmlTextWriter 
= new System.Web.UI.HtmlTextWriter(oStringWriter);
        dg.RenderControl(oHtmlTextWriter);
        Response.Write(oStringWriter.ToString());
        Response.End();
    }

    
//重载VerifyRenderingInServerForm方法,调用页面必须加入否则会提示错误
   public override void VerifyRenderingInServerForm(Control control)
    

    }

    
//调用方法 OutWord(Student, "File name.doc");
    protected void Button1_Click(object sender, EventArgs e)
    
{       
        OutWord(Student, 
"File name.doc");

    }

    
//调用方法 OutExcel(Student, "File name.xls"); 
    protected void Button2_Click(object sender, EventArgs e)
    
{
        OutExcel(Student, 
"File name.xls");        
    }

原网址:http://hi.baidu.com/sharp528108/blog/item/03217012279e3c52f819b884.html
为了避免标头出现乱码
用下边代码对标题进行编码
System.Web.HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8)+".xls";

转载于:https://www.cnblogs.com/sunheyubo/archive/2008/03/27/1124903.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值