ASP.NET中将数据输出到Excel

分类: asp.net技巧   出处:iocblog整理  更新时间:2008-12-10   添加到收藏  

  近来,在开发iso文件管理系统的时候,曾经遇到过要将aspx直接输出到excel的需求,现将经验所得与大家分享。 其实,利用asp.net输出指定内容的word、excel、txt、htm等类型的文档很容易的。主要分为三步来完成。

  一、定义文档类型、字符编码

response.clear();
response.buffer= true;
response.charset="utf-8";

//下面这行很重要, attachment 参数表示作为附件下载,您可以改成 online在线打开

//filename=fileflow.xls 指定输出文件的名称,注意其扩展名和指定文件类型相符,可以为:.doc || .xls || .txt ||.htm

response.appendheader("content-disposition","attachment;filename=fileflow.xls");
response.contentencoding=system.text.encoding.getencoding("utf-8");

//response.contenttype指定文件类型 可以为application/ms-excel || application/ms-word || application/ms-txt || application/ms-html || 或其他浏览器可直接支持文档

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);[www.iocblog.net 来源]

  三、将目标数据绑定到输入流输出

this.rendercontrol(ohtmltextwriter);

//this 表示输出本页,你也可以绑定datagrid,或其他支持obj.rendercontrol()属性的控件

response.write(ostringwriter.tostring());[www.iocblog.net 来源]
response.end();

  总结:本例程在microsoft visual studio .net 2003平台下测试通过,适用于c#和vb,当采用vb的时候将 this 关键字改成 me 。


Tag: Excel



文章整理:iocblog
版权申明:本站文章均来自网络,如有侵权,请联系我们,我们收到后立即删除,谢谢!
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有。