• 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();
        }
  • 相关阅读:
    菜鸟二三事
    访问 IIS 元数据库失败的问题(转)
    SQL Server 2005/2008还原数据库时遇到的问题(转)
    ME54N审批、撤批触发增强点:ME_RE…
    南通网站建设整理:最新搜索引擎登录口保证都可以用
    调试mvc的源代码
    c#委托(delegate)揭秘
    ASP.NET 应用程序生命周期概述
    JavaScript Array(数组)对象
    jQuery.each
  • 原文地址:https://www.cnblogs.com/sizhizhiyue/p/4825575.html
Copyright © 2020-2023  润新知