zoukankan      html  css  js  c++  java
  • asp.net后台导出excel的方法:使用response导出excel

    完整程序:

    一:调用方法:CreateExcel(newDt, "application/ms-excel", "FileName");

    /// <summary>
        /// DataTable中的数据导出到Excel并下载
        /// </summary>
        /// <param name="dt">要导出的DataTable</param>
        /// <param name="FileType">类型</param>
        /// <param name="FileName">Excel的文件名</param>
        public void CreateExcel(DataTable dt, string FileType, string FileName)
        {
            Response.Clear();
            Response.Charset = "UTF-8";
            Response.Buffer = true;
            Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
            Response.AppendHeader("Content-Disposition", "attachment;filename="" + System.Web.HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8) + ".xls"");
            Response.ContentType = FileType;
    
            string colHeaders = string.Empty;
            string ls_item = string.Empty;
            DataRow[] myRow = dt.Select();
            int i = 0;
            int cl = dt.Columns.Count;
            
            //写入方法一
            //写入标题等信息
            ls_item +=  Label2.Text  + "			
    
    ";
            Response.Output.Write(ls_item);
            ls_item = string.Empty;
            ls_item +=  txtStart.Text + "			";
            ls_item +=  DropEnterprise.SelectedItem  + "
    ";
            Response.Output.Write(ls_item);
            ls_item = string.Empty;
            //写入段标题
            for (i = 0; i < cl; i++)
            {
                if (i == (cl - 1))
                {
                    ls_item += dt.Columns[i].ColumnName.ToString() + "
    ";
                }
                else
                {
                    ls_item += dt.Columns[i].ColumnName.ToString() + "	";
                }
            }
            Response.Output.Write(ls_item);
            ls_item = string.Empty;
    
            foreach (DataRow row in myRow)
            {
                for (i = 0; i < cl; i++)
                {
                    if (i == (cl - 1))
                    {
                        ls_item += row[i].ToString() + "
    ";
                    }
                    else
                    {
                        ls_item += row[i].ToString() + "	";
                    }
                }
                //一行一行的写入
                Response.Output.Write(ls_item);
                ls_item = string.Empty;
            }
    
            Response.Output.Flush();
            Response.End();
        }
  • 相关阅读:
    python版本切换及添加路径
    python下载及安装步骤
    day01计算机基础-python解释器-pycharm介绍
    查看pycharm有效期
    对于Makefile的基本使用
    Shell命令整理
    一起来免费听无损高品质音乐吧!
    记录 解决ubuntu16.04 ‘E: 无法获得锁 /var/lib/dpkg/lock-frontend
    Ubuntu16手动安装OpenStack——keystone篇
    python3中的RE(正则表达式)
  • 原文地址:https://www.cnblogs.com/sizhizhiyue/p/4825575.html
Copyright © 2011-2022 走看看