C#DataGrid Export data to Excel

来源:互联网 发布:网店美工培训班 编辑:程序博客网 时间:2024/04/27 20:37
方法1

public void DataGridToExcel(DataGrid dgExport , HttpResponse response){  //clean up the response.object  response.Clear();  response.Charset = "";  //'set the response mime type for excel  response.ContentType = "application/vnd.ms-excel";  //'create a string writer  System.IO.StringWriter stringWrite = new System.IO.StringWriter();  //create an htmltextwriter which uses the stringwriter  System.Web.UI.HtmlTextWriter htmlWrite = new System.Web.UI.HtmlTextWriter(stringWrite);  //instantiate a datagrid  DataGrid dg As New DataGrid();  //just set the input datagrid = to the new dg grid  dg = dgExport;  //I want to make sure there are no annoying gridlines  dg.GridLines = GridLines.None;  '//Make the header text bold  dg.HeaderStyle.Font.Bold = True;  //If needed, here's how to change colors/formatting at the component level  //dg.HeaderStyle.ForeColor = System.Drawing.Color.Black  //dg.ItemStyle.ForeColor = System.Drawing.Color.Black  //bind the modified datagrid  dg.DataBind();  //tell the datagrid to render itself to our htmltextwriter  dg.RenderControl(htmlWrite);  //output the html  response.Write(stringWrite.ToString);  response.End();}



方法2

        private void ExportAllDO()        {            //lvExportAll: DataGrid/GridView/ListView            lvExportAll.DataSource = GetAllItemDict();            lvExportAll.DataBind();            Response.Clear();            HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls");            HttpContext.Current.Response.Charset = "UTF-8";            HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;            HttpContext.Current.Response.ContentType = "application/ms-excel";            HttpContext.Current.Response.HeaderEncoding = System.Text.Encoding.UTF8;            lvExportAll.Page.EnableViewState = false;            System.IO.StringWriter tw = new System.IO.StringWriter();            System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);            lvExportAll.RenderControl(hw);            HttpContext.Current.Response.Write(tw.ToString());            HttpContext.Current.Response.End();        }


原创粉丝点击