上午给系统的订单管理部分添加了一个功能,把查询到的订单信息导出到excel,供管理员分析用。以前写的代码如下:
response.clear();
response.bufferoutput = true;
response.charset = "gb2312";
response.appendheader("content-disposition","attachment;filename = filename.xls");
response.contentencoding = encoding.getencoding("gb2312");
response.contenttype = "application/ms-excel";
this.enableviewstate = false;
system.globalization.cultureinfo myinfo = new system.globalization.cultureinfo("zh-cn", true);
stringwriter osw = new stringwriter(myinfo);
htmltextwriter ohtw = new htmltextwriter(osw);
dgqueryresult.rendercontrol(ohtw);
response.write(osw);
response.end();
我的查询用了分页,客户要求把所有查询到的数据都导出到excel,所以不能象以前那样通过把控件的内容导出到excel来实现此功能,于是把代码改成这样:
response.clear();
response.bufferoutput = true;
response.charset = "gb2312";
response.appendheader("content-disposition","attachment;filename = 订单.xls");
response.contentencoding = system.text.encoding.getencoding("gb2312");
response.contenttype = "application/ms-excel";
string strexcelheader = string.empty;
string strexcelitems;
if(viewstate["sql"] != null) // 取前面查询用的sql语句
{
// 取得各列标题,各标题之间以/t分割,最后一个列标题后加回车符
strexcelheader = "订单号/t经销商/t地区/t小类/t商品/t实付金额/t下单时间/t有效状态/t处理状态/t/n";
// 向http输出流中写入取得的数据信息
response.write(strexcelheader);
// 逐行处理查询结果数据
itdbhandle itdbhandle = new itdbhandle();
itdbhandle.querystring = viewstate["sql"].tostring();
sqldatareader reader = itdbhandle.executedatareader();
while(reader.read())
{
strexcelitems = string.empty;
strexcelitems += reader["orderid"].tostring() + "/t";
strexcelitems += reader["dealername"].tostring() + "/t";
strexcelitems += reader["city"].tostring() + "/t";
strexcelitems += reader["smallclassname"].tostring() + "/t";
strexcelitems += reader["brandname"].tostring() + reader["model"].tostring() + "/t";
strexcelitems += reader["totalprice"].tostring() + "/t";
strexcelitems += reader["orderdate"].tostring() + "/t";
strexcelitems += reader["isvalid"].tostring() + "/t";
strexcelitems += reader["dealstate"].tostring() +"/n";
response.write(strexcelitems);
}
reader.close();
response.end();
}
我这里只是简单的把查询到的数据以excel的形式write出来(当然也可以是其他格式,比如xml),对简单的需求足矣了,当然,用.net直接去操作excel文件也是很简单的,有很多这样的例子可以参考。
新闻热点
疑难解答