復制代碼 代碼如下:
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();
}