ASP.NET gridview导出excel,防止繁体产生有乱码的方式

//1.先引用比如 :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Diagnostics;
using System.Data.SqlClient;
using System.Web.UI;
using System.Web.UI.WebControls;

 
   /// <summary>
    /// 清除控件中的所有控件,以便导出Excel
    /// </summary>
    /// <param name="control"></param>
    public static void ClearControls(Control control)
    {
        for (int i = control.Controls.Count - 1; i >= 0; i--)
        {
            ClearControls(control.Controls[i]);

        }

        if (!(control is TableCell))
        {
            if (control.GetType().GetProperty("SelectedItem") != null)
            {
                LiteralControl literal = new LiteralControl();
                control.Parent.Controls.Add(literal);
                try
                {
                    literal.Text = (string)control.GetType().GetProperty("SelectedItem").GetValue(control, null);
                }
                catch
                {
                }
                control.Parent.Controls.Remove(control);
            }
            else if (control.GetType().GetProperty("Text") != null)
            {
                LiteralControl literal = new LiteralControl();
                control.Parent.Controls.Add(literal);
                literal.Text = (string)control.GetType().GetProperty("Text").GetValue(control, null);
                control.Parent.Controls.Remove(control);
            }
        }


        return;
    }


//重点导出功能,采用utf8 编码

    public static void ExportToExcelUnicode(GridView GV_PO,string ExcelName)
    {
        
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + ExcelName + ".xls");
        HttpContext.Current.Response.ContentType = "application/ms-excel";
        HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
        HttpContext.Current.Response.BinaryWrite(System.Text.Encoding.UTF8.GetPreamble());
        System.IO.StringWriter sw = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter hw = new HtmlTextWriter(sw);
        GV_PO.RenderControl(hw);
        HttpContext.Current.Response.Write(sw.ToString());
        HttpContext.Current.Response.End();

    }

//把上方两个功能建立在 APPCODE 中 ,单独的类,比如 ebs 

//然后可以调用:

EBS.ClearControls(GV_PO);
EBS.ExportToExcelUnicode(GV_PO, "ParmSetPallet" + DateAndTime.Now.ToString("yyyyMMddhhmmss"));

 
原文地址:https://www.cnblogs.com/cnishop/p/10721772.html