在做WEB报表时,很多时候会用到DataGrid控件来呈现数据,同时为了将数据暂时存下来,所以要导出Excel形式。以下是我在看到别人的后作了一点点更改而成的,相当于转帖。
原码如下:
public static bool DataGradExportExcel(Page pg,DataGrid dg)//把DATAGRID中的数据导入本地EXCEL中
  {
   try
   {
    pg.Response.Clear();
    pg.Response.Buffer= true;
    pg.Response.ContentType = "application/vnd.ms-excel";
    pg.Response.Charset = "";
    pg.EnableViewState = false;

    System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
    System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);

   
    dg.RenderControl(oHtmlTextWriter);

    pg.Response.Write(oStringWriter.ToString());

    pg.Response.End();
    return true;
   }
   catch
   {
    return false;
   }
  }