第一種,將DataGrid作為參數傳入,將DataGrid轉成Excel
public bool ToExcel(System.Web.UI.Control ctl)
{
try
{
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();
return true;
}
catch(Exception e)
{
_errormsg = e.Message;
return false;
}
}
第二種,直接將DataSet匯出成Excel
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);
resp.Charset ="UTF-8";
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")
{
resp.ContentType ="application/ms-excel";//image/JPEG;text/HTML;image/GIF;vnd.ms-excel/msword
//取得資料表各欄位標題,各標題之間以\t分割,最後一個欄位標題後加斷行符號符
for(i=0;i<dt.Columns.Count-1;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<dt.Columns.Count-1;i++)
ls_item +=row[i].ToString().Replace("\t","") + "\t";
ls_item += row[i].ToString().Replace("\t","") +"\n";
//當前行資料寫入HTTP輸出資料流,並且置空ls_item以便下行資料
resp.Write(ls_item);
ls_item="";
}
}
else
{
if(typeid=="2")
{
//從DataSet中直接匯出XML資料並且寫到HTTP輸出資料流中
resp.Write(ds.GetXml());
}
}
//寫緩衝區中的資料到HTTP標頭檔中
resp.End();
}