1、由dataset生成
public void CreateExcel(DataSet ds,string typeid,string FileName)
{
HttpResponse resp;
resp = Page.Response;
resp.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
resp.AppendHeader("Content-Disposition", "attachment;filename=" + FileName);
string colHeaders= "", ls_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 colHeaders+=dt.Columns[i].Caption.ToString()+"\t";
colHeaders +=dt.Columns[i].Caption.ToString() +"\n";
//向HTTP輸出流中寫入取得的數據信息
resp.Write(colHeaders);
//逐行處理數據
foreach(DataRow row in myRow)
{
//在當前行中,逐列獲得數據,數據之間以\t分割,結束時加回車符\n
for(i=0;i ls_item +=row[i].ToString() + "\t";
ls_item += row[i].ToString() +"\n";
//當前行數據寫入HTTP輸出流,並且置空ls_item以便下行數據
resp.Write(ls_item);
ls_item="";
}
}
else
{
if(typeid=="2")
{
//從DataSet中直接導出XML數據並且寫到HTTP輸出流中
resp.Write(ds.GetXml());
}
}
//寫緩沖區中的數據到HTTP頭文件中
resp.End();
}
2、由datagrid生成
public void ToExcel(System.Web.UI.Control ctl)
{
HttpContext.Current.Response.AppendHeader("Content-Disposition","attachment;filename=Excel.xls");
HttpContext.Current.Response.Charset ="UTF-8";
HttpContext.Current.Response.ContentEncoding =System.Text.Encoding.Default;
HttpContext.Current.Response.ContentType ="application/ms-excel";//image/JPEG;text/HTML;image/GIF;vnd.ms-excel/msword
ctl.Page.EnableViewState =false;
System.IO.StringWriter tw = new System.IO.StringWriter() ;
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter (tw);
ctl.RenderControl(hw);
HttpContext.Current.Response.Write(tw.ToString());
HttpContext.Current.Response.End();
}
用法:ToExcel(datagrid1);