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 = "";
//定義表對(duì)象與行對(duì)象,同時(shí)用DataSet對(duì)其值進(jìn)行初始化
DataTable dt = ds.Tables[0];
DataRow[] myRow = dt.Select();//可以類似dt.Select("id>10")之形式達(dá)到數(shù)據(jù)篩選目的
int i = 0;
int cl = dt.Columns.Count;
//取得數(shù)據(jù)表各列標(biāo)題,各標(biāo)題之間以\t分割,最后一個(gè)列標(biāo)題后加回車符
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輸出流中寫入取得的數(shù)據(jù)信息
//逐行處理數(shù)據(jù)
foreach (DataRow row in myRow)
{
//當(dāng)前行數(shù)據(jù)寫入HTTP輸出流,并且置空ls_item以便下行數(shù)據(jù)
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();
}