码迷,mamicode.com
首页 > Web开发 > 详细

.net 手动导出excel

时间:2015-06-25 11:55:24      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:

private StringWriter GetStringWriter(DataTable dt)
    {
        StringWriter sw = new StringWriter();
        //读列名   
        foreach (DataColumn dc in dt.Columns)
            sw.Write(dc.ColumnName + "\t");

        //读列值   
        //重新的一行   
        sw.Write(sw.NewLine);
        if (dt != null)
        {
            foreach (DataRow dr in dt.Rows)
            {
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    sw.Write(dr[i].ToString() + "\t");
                }
                sw.Write(sw.NewLine);
            }
        }
        sw.Close();

        return sw;
    }

    protected void ExcelImport(DataTable dt, string ExportFileName)
    {
        StringWriter sw = GetStringWriter(dt);
        //当前编码   
        HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
        //把输出的文件名进行编码   
        string fileName = HttpUtility.UrlEncode(ExportFileName, System.Text.Encoding.UTF8);
        //文件名   
        string str = "attachment;filename=" + fileName + ".xls";
        //  sw.ContentType = "application/vnd.ms-excel";
        //把文件头输出,此文件头激活文件下载框   
        HttpContext.Current.Response.AppendHeader("Content-Disposition", str);//http报头文件   
        HttpContext.Current.Response.ContentType = "application/ms-excel";
        this.Page.EnableViewState = false;

        Response.Write(sw);
        Response.End();
    }

 

.net 手动导出excel

标签:

原文地址:http://www.cnblogs.com/110abcd/p/4599438.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!