NET页面导出Excel实例代码
public static void createexcel(dataset ds)
{
string filename = datetime.now.tostring("yyyymmddhhmmssff") + ".xls";
httpcontext.current.response.contentencoding = system.text.encoding.getencoding("gb2312");
httpcontext.current.response.appendheader("content-disposition", "attachment;filename=" + filename);
string colheaders = "", ls_item = "";
//定义表对象与行对象,同时用dataset对其值进行初始化
datatable dt = ds.tables[0];
datarow[] myrow = dt.select();//可以类似dt.select("id>10")之形式达到数据筛选目的
int i = 0;
int cl = dt.columns.count;
//取得数据表各列标题,各标题之间以\t分割,最后一个列标题后加回车符
for (i = 0; i < cl; i++)
{
if (i == (cl - 1))//最后一列,加\n
{
colheaders += dt.columns[i].caption.tostring() + "\n";
}
else
{
colheaders += dt.columns[i].caption.tostring() + "\t";
}
}
httpcontext.current.response.write(colheaders);
//向http输出流中写入取得的数据信息
//逐行处理数据
foreach (datarow row in myrow)
{
//当前行数据写入http输出流,并且置空ls_item以便下行数据
for (i = 0; i < cl; i++)
{
if (i == (cl - 1))//最后一列,加\n
{
ls_item += row[i].tostring() + "\n";
}
else
{
ls_item += row[i].tostring() + "\t";
}
}
httpcontext.current.response.write(ls_item);
ls_item = "";
}
httpcontext.current.response.end();
}