码迷,mamicode.com
首页 > 其他好文 > 详细

导出excel

时间:2014-07-16 21:22:39      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:http   文件   os   数据   for   io   

 public bool LendOutExcel(string strFileName, DataTable DT)
        {
            try
            {
                //清除Response缓存内容
                HttpContext.Current.Response.Clear();
                //缓存输出,并在完成整个响应之后将其发送
                HttpContext.Current.Response.Buffer = true;
                //strFileName指定输出文件的名称,注意其扩展名和指定文件类型相符,可以为:.doc .xls .txt .htm
                strFileName = strFileName + ".xls";
                //设置输出流的HTPP字符集,确定字符的编码格式
                //HttpContext.Current.Response.Charset = "UTF-8";
                HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
                //下面这行很重要, attachment 参数表示作为附件下载,您可以改成 online在线打开
                HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(strFileName));
                //Response.ContentType指定文件类型.可以为application/ms-excel,application/ms-word,application/ms-txt,application/ms-html或其他浏览器可直接支持文档
                HttpContext.Current.Response.ContentType = "application/ms-excel";
                string colHeaders = "", ls_item = "";
                int i = 0;
                //定义表对象与行对像,同时用DataSet对其值进行初始化
                DataRow[] myRow = DT.Select("");
                //取得数据表各列标题,各标题之间以\t分割,最后一个列标题后加回车符
                for (i = 0; i < DT.Columns.Count - 1; i++)
                {
                    colHeaders += DT.Columns[i].Caption.ToString() + "\t";
                }
                colHeaders += DT.Columns[i].Caption.ToString() + "\n";
                //向HTTP输出流中写入取得的数据信息
                HttpContext.Current.Response.Write(colHeaders);
                //逐行处理数据
                foreach (DataRow row in myRow)
                {
                    //在当前行中,逐列获得数据,数据之间以\t分割,结束时加回车符\n
                    for (i = 0; i < DT.Columns.Count - 1; i++)
                        ls_item += row[i].ToString() + "\t";
                    ls_item += row[i].ToString() + "\n";
                    //当前行数据写入HTTP输出流,并且置空ls_item以便下行数据   
                    HttpContext.Current.Response.Write(ls_item);
                    ls_item = "";
                }
                //写缓冲区中的数据到HTTP头文件中
                HttpContext.Current.Response.End();
                return true;
            }
            catch
            {
                return false;
            }
        }

导出excel,布布扣,bubuko.com

导出excel

标签:http   文件   os   数据   for   io   

原文地址:http://www.cnblogs.com/yuzk/p/3835972.html

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