zoukankan      html  css  js  c++  java
  • asp.net 把数据导出为excel

    本篇介绍c#中如何使用DataTable导出Excel,至于其他的导出方法,这里不作介绍!

    1.首页从数据库读取数据,得到DataTable:

    DataTable dt = HelperExecuteSql.Query("select ID,name,author,newsContent,inDate from newsInfo").Tables[0];

    2.使用StringWriter类:将信息写入字符串(其命名空间为:System.IO)

    private StringWriter GetStringWriter(DataTable dt)
        {
            StringWriter sw = new StringWriter();
            //读列名,也可以自定义列名(即导出excel的表头)
            //foreach (DataColumn dc in dt.Columns)
            //{ sw.Write(dc.ColumnName + "	");}
    //表头,自定义 sw.Write("序号 "); sw.Write("新闻名 "); sw.Write("作者 "); sw.Write("新闻内容 "); sw.Write("上传时间 ");//读列值,重新的一行 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() + " "); } sw.Write(sw.NewLine); } } sw.Close(); return sw; }

     3. ExcelImport(dt, "新闻列表");

    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";
            //把文件头输出,此文件头激活文件下载框  
            HttpContext.Current.Response.AppendHeader("Content-Disposition", str);//http报头文件  
            HttpContext.Current.Response.ContentType = "application/ms-excel";
            this.Page.EnableViewState = false;
            Response.Write(sw);
            Response.End();
        }
    

      

  • 相关阅读:
    Shortcut key for WPF
    Make webclient support upload the large file which are larger than 1G
    Decodes a QuotedPrintable encoded string
    C# USB Detection winform and WPF
    [转] 线程同步
    C# x86应用x64系统上读取x64位应用的注册表
    CSS Sprites图片拼合生成器实现思路
    python 复制文件
    Resources: Tips of Notepad++
    ASP.net MVC与RESTful ROA的思想还是有点区别的
  • 原文地址:https://www.cnblogs.com/qk2014/p/3980717.html
Copyright © 2011-2022 走看看