private void TOEXCEL_Click(object sender, System.EventArgs e)
{
CreateExcel(this.ds,"1","Exit_List.xls");//关键是这里不知道DataSet ds如何赋值
}
public void CreateExcel(DataSet ds,string typeid,string FileName)
{
HttpResponse resp;
resp = Page.Response;
resp.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
resp.ContentType = "application/ms-excel";
resp.AddHeader("Content-Disposition",
"attachment; filename=" + System.Web.HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8) + ".xls");
this.EnableViewState = false;
string colHeaders="",Is_item="";
int i=0;
//定义表对象与行对象,同时使用DataSet对其值进行初始化
DataTable dt = ds.Tables[0];
DataRow[] myRow =dt.Select("");
//typeid=="1"时导出为Excel格式文件;typeid=="2"时导出为XML文件
if(typeid=="1")
{
//取得数据表各列标题,标题之间以\t分割,最后一个列标题后加回车符
for(i=0;i<dt.Columns.Count;i++)
{
colHeaders += dt.Columns[i].Caption.ToString()+"\t";
}
colHeaders += "\n";
resp.Write(colHeaders);
//逐行处理数据
foreach(DataRow row in myRow)
{
//在当前行中,逐列取得数据,数据之间以\t分割,结束时加回车符\n
for(i=0;i<dt.Columns.Count;i++)
{
Is_item += row[i].ToString()+"\t";
}
Is_item += "\n";
resp.Write(Is_item);
Is_item = "";
}
}
else
{
if(typeid=="2")
{
//从DataSet中直接导出XML数据并且写到HTTP输出流中
resp.Write(ds.GetXml());
}
}
//写缓冲区中的数据到HTTP头文件中
resp.End();
}