惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

H
Help Net Security
博客园 - Franky
GbyAI
GbyAI
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
爱范儿
爱范儿
IT之家
IT之家
酷 壳 – CoolShell
酷 壳 – CoolShell
aimingoo的专栏
aimingoo的专栏
博客园_首页
MongoDB | Blog
MongoDB | Blog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Recent Announcements
Recent Announcements
Scott Helme
Scott Helme
有赞技术团队
有赞技术团队
M
MIT News - Artificial intelligence
C
CERT Recently Published Vulnerability Notes
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
Jina AI
Jina AI
F
Fortinet All Blogs
N
Netflix TechBlog - Medium
L
LangChain Blog
L
LINUX DO - 最新话题
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
H
Hacker News: Front Page
MyScale Blog
MyScale Blog
P
Palo Alto Networks Blog
G
Google Developers Blog
Google DeepMind News
Google DeepMind News
AI
AI
T
Troy Hunt's Blog
Microsoft Azure Blog
Microsoft Azure Blog
阮一峰的网络日志
阮一峰的网络日志
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Vercel News
Vercel News
Microsoft Security Blog
Microsoft Security Blog
罗磊的独立博客
S
Secure Thoughts
大猫的无限游戏
大猫的无限游戏
博客园 - 叶小钗
人人都是产品经理
人人都是产品经理
Blog — PlanetScale
Blog — PlanetScale
博客园 - 司徒正美
Apple Machine Learning Research
Apple Machine Learning Research
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
博客园 - 三生石上(FineUI控件)
S
Security @ Cisco Blogs
Cloudbric
Cloudbric
E
Exploit-DB.com RSS Feed
Attack and Defense Labs
Attack and Defense Labs

博客园 - 从无到有.NET

[转帖]如何提升JavaScript操作DOM的效率 FCKEditor使用RequiredFieldValidator验证时必须点击两次的解决办法 揭开正则表达式的神秘面纱 比较完整的一个 Ajax 类库汇总 解决“未能创建 Mutex”的问题 解决ASP.NET的进程帐户没有访问IIS的权限 MSN Messenger去广告和其他修改方法 - 从无到有.NET - 博客园 如何取消“本页不但包含安全的内容,也包含不安全的内容。是否显示不安全的内容。” 的提示 ASP.NET 中的正则表达式 asp.net TreeView安装、使用(如何将TreeView打包发布)(带CheckBox选择框的TreeView的初始化,TreeView客户端操作:选择父节点后自动选择所有子节点,子节点选择后自动选择父节点)(TreeView节点精确定位) 使用C#调用外部Ping命令获取网络连接情况 在.Net中嵌入资源文件到程序集中 RegularExpressionValidator 【原创】如何去掉有源代码管理的项目中的相关信息 关于PHP--session的问题集锦解决方案 php和asp对象的等价关系 My SQL出错代码及出错信息对照 Windows 环境下的 PHP5 与 Apache 服务器的配置 - 从无到有.NET php.ini中文解释
【转贴】datagrid数据导出到excel文件给客户端下载的几种方法
从无到有.NET · 2006-05-06 · via 博客园 - 从无到有.NET

作者:LoveCherry 技术无极限
原文地址:http://lovecherry.cnblogs.com/archive/2005/03/25/125519.aspx

方法一:导出到csv文件,存放在服务器端任一路径,然后给客户下载

优点:
1、可以进行身份认证后给客户下载,如果放到非web目录就没有对应的url,客户无法随时下载。
2、也是因为生成了文件,所以占用了服务器的空间,但是可以把文件名存放到数据库,再次给客户下载的时候不需要重复生成文件。
3、csv文件是文本文件,逗号隔开字段,回车隔开行,易于数据导入导出。

实现方法:

   SqlConnection conn=new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["conn"]);
   SqlDataAdapter da=new SqlDataAdapter("select * from tb1",conn);
   DataSet ds=new DataSet();
   da.Fill(ds,"table1");
   DataTable dt=ds.Tables["table1"];
   string name=System.Configuration.ConfigurationSettings.AppSettings["downloadurl"].ToString()+DateTime.Today.ToString("yyyyMMdd")+new Random(DateTime.Now.Millisecond).Next(10000).ToString()+".csv";//存放到web.config中downloadurl指定的路径,文件格式为当前日期+4位随机数
   FileStream fs=new FileStream(name,FileMode.Create,FileAccess.Write);
   StreamWriter sw=new StreamWriter(fs,System.Text.Encoding.GetEncoding("gb2312"));
   sw.WriteLine("自动编号,姓名,年龄");
   foreach(DataRow dr in dt.Rows)
   {
    sw.WriteLine(dr["ID"]+","+dr["vName"]+","+dr["iAge"]);
   }
   sw.Close();
   Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(name));
   Response.ContentType = "application/ms-excel";// 指定返回的是一个不能被客户端读取的流,必须被下载
   Response.WriteFile(name); // 把文件流发送到客户端
   Response.End();

方法二:导出到csv文件,不存放到服务器,直接给浏览器输出文件流

优点:
1、随时生成,不需要占用资源
2、可以结合身份认证
3、同样利于数据交换

实现方法:
SqlConnection conn=new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["conn"]);
   SqlDataAdapter da=new SqlDataAdapter("select * from tb1",conn);
   DataSet ds=new DataSet();
   da.Fill(ds,"table1");
   DataTable dt=ds.Tables["table1"];
   StringWriter sw=new StringWriter();
   sw.WriteLine("自动编号,姓名,年龄");
   foreach(DataRow dr in dt.Rows)
   {
    sw.WriteLine(dr["ID"]+","+dr["vName"]+","+dr["iAge"]);
   }
   sw.Close();
   Response.AddHeader("Content-Disposition", "attachment; filename=test.csv");
   Response.ContentType = "application/ms-excel";
   Response.ContentEncoding=System.Text.Encoding.GetEncoding("GB2312");
   Response.Write(sw);
   Response.End();

对方法一,二补充一点,如果你希望导出的是xls文件分隔符用\t就可以了,不要用逗号

代码修改如下:
sw.WriteLine("自动编号\t姓名\t年龄");
   foreach(DataRow dr in dt.Rows)
   {
    sw.WriteLine(dr["ID"]+"\t"+dr["vName"]+"\t"+dr["iAge"]);
   }
另外,修改输出的文件扩展名为xls即可。


方法三:从datagrid导出html代码,生成excel文件,给客户端下载

优点:
1、有固定的格式,样子好看(datagrid的样子)

局限性:
1、不适合数据交换,里面有html代码,比较乱,没有固定格式
2、datagrid不能有分页、排序等,否则出错

实现方法:
Response.Clear();
   Response.Buffer= false;
   Response.Charset="GB2312";
   Response.AppendHeader("Content-Disposition","attachment;filename=test.xls");
   Response.ContentEncoding=System.Text.Encoding.GetEncoding("GB2312");    Response.ContentType = "application/ms-excel";    this.EnableViewState = false;
   System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
   System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
   this.DataGrid1.RenderControl(oHtmlTextWriter);
   Response.Write(oStringWriter.ToString());
   Response.End();

在这里说明一点:有的网友反映代码出现“没有dr["id"]”之类的错误,这个代码是按照我的数据结构来写的,到时候相关的字段要换成你自己的才是。

还有就是如果文件名需要中文的话,这么修改Response.AddHeader("Content-Disposition", "attachment; filename="+System.Web.HttpUtility.UrlEncode("中文",System.Text.Encoding.UTF8)+".xls");