datagrid數(shù)據(jù)導(dǎo)出到excel文件給客戶端下載的幾種方法
2024-07-21 02:24:05
供稿:網(wǎng)友
方法一:導(dǎo)出到csv文件,存放在服務(wù)器端任一路徑,然后給客戶下載
優(yōu)點(diǎn):
1、可以進(jìn)行身份認(rèn)證后給客戶下載,如果放到非web目錄就沒(méi)有對(duì)應(yīng)的url,客戶無(wú)法隨時(shí)下載。
2、也是因?yàn)樯闪宋募?,所以占用了服?wù)器的空間,但是可以把文件名存放到數(shù)據(jù)庫(kù),再次給客戶下載的時(shí)候不需要重復(fù)生成文件。
3、csv文件是文本文件,逗號(hào)隔開(kāi)字段,回車隔開(kāi)行,易于數(shù)據(jù)導(dǎo)入導(dǎo)出。
實(shí)現(xiàn)方法:
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指定的路徑,文件格式為當(dāng)前日期+4位隨機(jī)數(shù)
filestream fs=new filestream(name,filemode.create,fileaccess.write);
streamwriter sw=new streamwriter(fs,system.text.encoding.getencoding("gb2312"));
sw.writeline("自動(dòng)編號(hào),姓名,年齡");
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";// 指定返回的是一個(gè)不能被客戶端讀取的流,必須被下載
response.writefile(name); // 把文件流發(fā)送到客戶端
response.end();
方法二:導(dǎo)出到csv文件,不存放到服務(wù)器,直接給瀏覽器輸出文件流
優(yōu)點(diǎn):
1、隨時(shí)生成,不需要占用資源
2、可以結(jié)合身份認(rèn)證
3、同樣利于數(shù)據(jù)交換
實(shí)現(xiàn)方法:
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("自動(dòng)編號(hào),姓名,年齡");
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();
方法三:從datagrid導(dǎo)出html代碼,生成excel文件,給客戶端下載
優(yōu)點(diǎn):
1、有固定的格式,樣子好看(datagrid的樣子)
局限性:
1、不適合數(shù)據(jù)交換,里面有html代碼,比較亂,沒(méi)有固定格式
2、datagrid不能有分頁(yè)、排序等,否則出錯(cuò)
實(shí)現(xiàn)方法:
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();