• Table导出为xls,doc,txt,htm方法


       经常遇到将DataTable中的数据导到一个excel或者doc等常用文件格式的情况,google了一些资料,总结一下:
    将DataTable中的内容写成HTML,Table格式,然后用下面函数,导出。
     1private void ExportExcel(string filename, string table) //table为DataTable写成HTML格式的字符串。
     2  {
     3   Response.Clear();
     4   Response.Buffer = true;
     5   Response.Charset = "utf-8"//定义文档类型、字符编码
     6   //attachment 参数表示作为附件下载, 可以改成 online 在线打开
     7   //filename = 指定输出文件的名称, 注意其扩展名和指定文件类型相符, 可为:.doc  .xls  .txt .htm
     8   Response.AppendHeader("Content-Disposition","attachment;filename=" + filename + ".xls");
     9   Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
    10   //Response.ContentType 可以为 application/ms-excel  application/ms-word  application/ms-txt  application/ms-html  或其他浏览器可直接支持文档 
    11   Response.ContentType = "application/ms-excel";
    12   this.EnableViewState = false;
    13    StringWriter oStringWriter = new System.IO.StringWriter();  //定义一个输入流
    14   HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
    15     this.RenderControl(oHtmlTextWriter);  //将目标数据绑定到输入流输出
    16   //this 表示输出本页, 也可以绑定 datagrid, 或其他支持 obj.RenderControl() 属性的控件
    17   Response.Write(table);
    18   Response.End();
    19  }
  • 相关阅读:
    基于【 Docker】四 || Docker常用镜像安装
    【静态延迟加载】self关键字和static关键字的区别
    【php设计模式】单例模式
    为什么要使用 SPL中的 SplQueue实现队列
    php中连接tcp服务的三种方式
    使用rsync工具构建php项目管理平台
    php 求两个数组的差集应该注意的事情
    lnmp环境快速搭建及原理解析
    nginx + lua 限制ip地址访问
    mysql主从复制搭建
  • 原文地址:https://www.cnblogs.com/zjy/p/402991.html
Copyright © 2020-2023  润新知