DataTable数据导出成Excel文件的小例子
///
/// 将datatable中的数据导出到指定的excel文件中
///
/// web页面对象
/// 包含被导出数据的datatable对象
/// excel文件的名称
public static void export(system.web.ui.page page,system.data.datatable tab,string filename)
{
system.web.httpresponse httpresponse = page.response;
system.web.ui.webcontrols.datagrid datagrid=new system.web.ui.webcontrols.datagrid();
datagrid.datasource=tab.defaultview;
datagrid.allowpaging = false;
datagrid.headerstyle.backcolor = system.drawing.color.green;
datagrid.headerstyle.horizontalalign = horizontalalign.center;
datagrid.headerstyle.font.bold = true;
datagrid.databind();
httpresponse.appendheader("content-disposition","attachment;filename="+httputility.urlencode(filename,system.text.encoding.utf8)); //filename="*.xls";
httpresponse.contentencoding=system.text.encoding.getencoding("gb2312");
httpresponse.contenttype ="application/ms-excel";
system.io.stringwriter tw = new system.io.stringwriter() ;
system.web.ui.htmltextwriter hw = new system.web.ui.htmltextwriter (tw);
datagrid.rendercontrol(hw);
string filepath = page.server.mappath("..")+"//files//" +filename;
system.io.streamwriter sw = system.io.file.createtext(filepath);
sw.write(tw.tostring());
sw.close();
downfile(httpresponse,filename,filepath);
httpresponse.end();
}
private static bool downfile(system.web.httpresponse response,string filename,string fullpath)
{
try
{
response.contenttype = "application/octet-stream";
response.appendheader("content-disposition","attachment;filename=" +
httputility.urlencode(filename,system.text.encoding.utf8) + ";charset=gb2312");
system.io.filestream fs= system.io.file.openread(fullpath);
long flen=fs.length;
int size=102400;//每100k同时下载数据
byte[] readdata = //www.jb51.net/yongle_tianya/archive/2011/10/24/new byte[size];//指定缓冲区的大小
if(size>flen)size=convert.toint32(flen);
long fpos=0;
bool isend=false;
while (!isend)
{
if((fpos+size)>flen)
{
size=convert.toint32(flen-fpos);
readdata = //www.jb51.net/yongle_tianya/archive/2011/10/24/new byte[size];
isend=true;
}
fs.read(readdata, 0, size);//读入一个压缩块
response.binarywrite(readdata);
fpos+=size;
}
fs.close();
system.io.file.delete(fullpath);
return true;
}
catch
{
return false;
}
}
上一篇: python 调用c语言函数的方法
下一篇: Python 基础教程之闭包的使用方法