asp.net – Gridview导出到xls office97-2003版本 -UTF-8格式-可防止gridview中的繁体等字符乱码现象

asp.net 建立一个button,名称为btnToExcel,后台cs的click事件如下

//导出到Excel
protected void btnToExcel_Click(object sender, EventArgs e)
{
GV_PO.AllowPaging = false;
bind(); //你需要捞取的查询语句,自定义
ClearControls(GV_PO);  //先清空格式,可能gridview中有文本框,超链接等 GV_PO为 gridview的id
ExportToExcelUnicode(GV_PO, "ReportHeader" + DateAndTime.Now.ToString("yyMMddhhmmss"));  //导出xls

}

ClearControls函数:

/// <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;
    }

ExportToExcelUnicode 函数:

    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();

    }

 

 

 

 

----欢迎转载----
THE END
分享
二维码
< <上一篇
下一篇>>