public void CreateExcel(DataSet ds,string FileName)
{
HttpResponse resp;
resp = Page.Response;
resp.ContentType = "application/vnd.ms-excel";
resp.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
resp.AppendHeader("Content-Disposition", "attachment;filename=" + FileName+".xls");
string colHeaders= "<style>td{white-space:nowrap;}</style><table><tr>", ls_item="";
int i=0;
//定义表对象与行对像,同时用DataSet对其值进行初始化
DataTable dt=ds.Tables[0];
DataRow[] myRow=dt.Select("");
//取得数据表各列标题,各标题之间以\t分割,最后一个列标题后加回车符
for (i = 0; i < dt.Columns.Count; i++)
{
colHeaders += "<td>"+dt.Columns[i].Caption.ToString() + "</td>";
}
colHeaders +="</tr>";
//向HTTP输出流中写入取得的数据信息
resp.Write(colHeaders);
//逐行处理数据
foreach(DataRow row in myRow)
{
ls_item += "<tr>";
//在当前行中,逐列获得数据,数据之间以\t分割,结束时加回车符\n
for (i = 0; i < dt.Columns.Count; i++)
{
ls_item += "<td>"+row[i].ToString() + "</td>";
}
ls_item += "</tr>";
//当前行数据写入HTTP输出流,并且置空ls_item以便下行数据
resp.Write(ls_item);
ls_item="";
}
resp.Write("</table>");
//写缓冲区中的数据到HTTP头文件中
resp.End();
}
{
HttpResponse resp;
resp = Page.Response;
resp.ContentType = "application/vnd.ms-excel";
resp.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
resp.AppendHeader("Content-Disposition", "attachment;filename=" + FileName+".xls");
string colHeaders= "<style>td{white-space:nowrap;}</style><table><tr>", ls_item="";
int i=0;
//定义表对象与行对像,同时用DataSet对其值进行初始化
DataTable dt=ds.Tables[0];
DataRow[] myRow=dt.Select("");
//取得数据表各列标题,各标题之间以\t分割,最后一个列标题后加回车符
for (i = 0; i < dt.Columns.Count; i++)
{
colHeaders += "<td>"+dt.Columns[i].Caption.ToString() + "</td>";
}
colHeaders +="</tr>";
//向HTTP输出流中写入取得的数据信息
resp.Write(colHeaders);
//逐行处理数据
foreach(DataRow row in myRow)
{
ls_item += "<tr>";
//在当前行中,逐列获得数据,数据之间以\t分割,结束时加回车符\n
for (i = 0; i < dt.Columns.Count; i++)
{
ls_item += "<td>"+row[i].ToString() + "</td>";
}
ls_item += "</tr>";
//当前行数据写入HTTP输出流,并且置空ls_item以便下行数据
resp.Write(ls_item);
ls_item="";
}
resp.Write("</table>");
//写缓冲区中的数据到HTTP头文件中
resp.End();
}
每条数据在Excel中都显示为一行,效果图如下: