欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

.net中将DataTable导出到word、Excel、txt、htm的方法

程序员文章站 2022-06-21 19:51:12
dt:datatable strfile:filename strext:type private void gridexport(datatable dt, string s...

dt:datatable

strfile:filename

strext:type


private void gridexport(datatable dt, string strfile, string strext)
{
string strapptype = "";
switch (strext)
{
case "xls":
strapptype = "application/ms-excel";
break;
case "doc":
strapptype = "application/ms-word";
break;
case "txt":
strapptype = "application/ms-txt";
break;
case "html":
case "htm":
strapptype = "application/ms-html";
break;
default: return;
}
gridview mygridview = new gridview();
mygridview.datasource = dt;
mygridview.databind();
httpcontext.current.response.clear();
httpcontext.current.response.buffer = true;
httpcontext.current.response.addheader("content-type", "text/html; charset=gb2312");
httpcontext.current.response.appendheader("content-disposition", string.format("attachment;filename={0}.{1}", httputility.urlencode(strfile,encoding.getencoding("gb2312")), strext));
httpcontext.current.response.contentencoding = system.text.encoding.getencoding("gb2312");
httpcontext.current.response.contenttype = strapptype;
//mygridview.page.enableviewstate = false;
//二、定义一个输入流
system.globalization.cultureinfo mycitrad = new system.globalization.cultureinfo("zh-cn", true);
system.io.stringwriter ostringwriter = new system.io.stringwriter(mycitrad);
system.web.ui.htmltextwriter ohtmltextwriter = new system.web.ui.htmltextwriter(ostringwriter);
//三、将目标数据绑定到输入流输出
mygridview.rendercontrol(ohtmltextwriter);
httpcontext.current.response.write(ostringwriter.tostring());
httpcontext.current.response.end();
}