none
Asp.net2.0利用GridView导出Excel里面的工作表名称sheet是乱码的,请求各位解决!!! RRS feed

  • 问题

  •     利用下面的方法倒出Excel,得到一个名为"下载信息.xls"文件,
    打开文件,里面的工作表名称变成了乱码:%e4%b8%8b%e8%bd%bd%e4%bf%a1%e6%81%af[1].xls
    很明显没有解码,请求解决。

        ExportToExcel("application/vnd.ms-excel", "下载信息.xls");
    
        public void ExportToExcel(string FileType, string FileName)
        {
            Response.Charset = "GB2312";
            Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
            Response.AppendHeader("Content-Disposition", "attachment;filename=" +
                HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8).ToString());
            Response.ContentType = FileType;            //MIME类型
            this.EnableViewState = false;               //设置页面的请求状态
            System.IO.StringWriter tw = new System.IO.StringWriter();      
            HtmlTextWriter hw = new HtmlTextWriter(tw); //以HTML结构的字符流
            GridView1.RenderControl(hw);   
            Response.Output.Write(tw.ToString());       //将字符串写入文本流
            Response.Flush();                           //缓冲流输出
            Response.End();
        }

    2009年12月2日 8:31

答案

  • 你好!

    我用你的方法试了下,是可行的。你看看是否是其它原因所致。

    <%@ Page Language="C#" AutoEventWireup="true" %>
    <%@ Import Namespace="System.Data" %>
    <script runat="server">
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                DataTable dt = new DataTable();
    
                dt.Columns.Add("Col1", typeof(Guid));
                dt.Columns.Add("Col2", typeof(Guid));
                dt.Columns.Add("Col3", typeof(Guid));
    
                while (dt.Rows.Count < 10)
                    dt.Rows.Add(new object[] { Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid() });
    
                this.GridView1.DataSource = dt;
                this.GridView1.DataBind();
            }
        }
    
        public override void VerifyRenderingInServerForm(Control control)
        {
            //base.VerifyRenderingInServerForm(control);
        }
    
        protected void Button1_Click(object sender, EventArgs e)
        {
            ExportToExcel("application/vnd.ms-excel", "下载信息.xls");
        }
    
        public void ExportToExcel(string FileType, string FileName)
        {
            Response.Charset = "GB2312";
            Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
            Response.AppendHeader("Content-Disposition", "attachment;filename=" +
                HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8).ToString());
            Response.ContentType = FileType;            //MIME类型
            this.EnableViewState = false;               //设置页面的请求状态
            System.IO.StringWriter tw = new System.IO.StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(tw); //以HTML结构的字符流
            GridView1.RenderControl(hw);
            Response.Output.Write(tw.ToString());       //将字符串写入文本流
            Response.Flush();                           //缓冲流输出
            Response.End();
        }
    </script>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title>无标题页</title>
    </head>
    <body>
        <form id="form1" runat="server">
        <asp:GridView ID="GridView1" runat="server">
        </asp:GridView>
        <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
        </form>
    </body>
    </html>
    


    知识改变命运,奋斗成就人生!
    2009年12月4日 1:57
    版主

全部回复

  • 你好!

    使用这种方式工作表名默认是和文件名一样的,你设置文件名时可以去掉  HttpUtility.UrlEncode, 或使用英文名代替。

    Response.AppendHeader("Content-Disposition", "attachment;filename=" + FileName);

    知识改变命运,奋斗成就人生!
    2009年12月2日 9:54
    版主
  • 谢谢!。。没有解决。。


    。。。。。。。。。。
    2009年12月3日 0:23
  • 试试下面代码, 注意使用HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Default;

    <%@ Page Language="C#" AutoEventWireup="true"  CodeFile="ToExcel.aspx.cs" Inherits="_Default" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title>Untitled Page</title>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
        
        </div>
        <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Output Excel" /> 
        
        <asp:GridView ID="GridView1" runat="server" AllowPaging="True" 
            onpageindexchanging="GridView1_PageIndexChanging" PageSize="10">
        </asp:GridView>
        </form>
    </body>
    </html>
    


    using System; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; using System.Xml; using System.Xml.Xsl; using System.Xml.XPath; using System.Web.UI; using System.IO; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!this.IsPostBack) { this.GridView1.DataSource = this.GenerateTab(); this.GridView1.DataBind(); } } public DataTable GenerateTab() { DataTable dt = new DataTable(); dt.Columns.Add("Cell1", typeof(string)); dt.Columns.Add("Cell2", typeof(string)); dt.Columns.Add("Cell3", typeof(string)); dt.Columns.Add("Cell4", typeof(string)); dt.Columns.Add("Cell5", typeof(string)); DataRow dr = dt.NewRow(); dr[0] = "1"; dr[1] = "2"; dr[2] = "3"; dr[3] = "4"; dr[4] = "5"; dt.Rows.Add(dr); DataRow dr1 = dt.NewRow(); dr1[0] = "10"; dr1[1] = "9"; dr1[2] = "8"; dr1[3] = "7"; dr1[4] = "6"; dt.Rows.Add(dr1); return dt; } protected void Button1_Click(object sender, EventArgs e) { int pageIndex = this.GridView1.PageIndex; this.GridView1.AllowPaging = false; this.GridView1.DataSource = this.GenerateTab(); this.GridView1.DataBind(); Export("test.xls", this.GridView1); this.GridView1.AllowPaging = true; this.GridView1.DataSource = this.GenerateTab(); this.GridView1.PageIndex = pageIndex; this.GridView1.DataBind(); } public override void VerifyRenderingInServerForm(Control control) { } protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e) { this.GridView1.DataSource = this.GenerateTab(); this.GridView1.PageIndex =e.NewPageIndex; this.GridView1.DataBind(); } public static void Export(string fileName, GridView gv) { HttpContext.Current.Response.Clear(); HttpContext.Current.Response.AddHeader( "content-disposition", string.Format("attachment; filename={0}", fileName)); HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Default; HttpContext.Current.Response.ContentType ="application/ms-excel"; //"application/ms-word"; using (StringWriter sw = new StringWriter()) { using (HtmlTextWriter htw = new HtmlTextWriter(sw)) { // Create a table to contain the grid Table table = new Table(); // include the gridline settings table.GridLines = gv.GridLines; // add the header row to the table if (gv.HeaderRow != null) { PrepareControlForExport(gv.HeaderRow); table.Rows.Add(gv.HeaderRow); } // add each of the data rows to the table foreach (GridViewRow row in gv.Rows) { PrepareControlForExport(row); table.Rows.Add(row); } // add the footer row to the table if (gv.FooterRow != null) { PrepareControlForExport(gv.FooterRow); table.Rows.Add(gv.FooterRow); } // render the table into the htmlwriter table.RenderControl(htw); // render the htmlwriter into the response HttpContext.Current.Response.Write(sw.ToString()); HttpContext.Current.Response.End(); } } } /// <summary> /// Replace any of the contained controls with literals /// </summary> /// <param name="control"></param> private static void PrepareControlForExport(Control control) { for (int i = 0; i < control.Controls.Count; i++) { Control current = control.Controls[i]; if (current is LinkButton) { control.Controls.Remove(current); control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text)); } else if (current is ImageButton) { control.Controls.Remove(current); control.Controls.AddAt(i, new LiteralControl((current as ImageButton).AlternateText)); } else if (current is HyperLink) { control.Controls.Remove(current); control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text)); } else if (current is DropDownList) { control.Controls.Remove(current); control.Controls.AddAt(i, new LiteralControl((current as DropDownList).SelectedItem.Text)); } else if (current is CheckBox) { control.Controls.Remove(current); control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False")); } if (current.HasControls()) { PrepareControlForExport(current); } } } }

    Microsoft Online Community Support
    2009年12月3日 3:28
  • 谢谢!  没有解决。

    楼上的方法只会让中文变成乱码
    。。。。。。。。。。
    2009年12月4日 0:36
  • 你好!

    我用你的方法试了下,是可行的。你看看是否是其它原因所致。

    <%@ Page Language="C#" AutoEventWireup="true" %>
    <%@ Import Namespace="System.Data" %>
    <script runat="server">
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                DataTable dt = new DataTable();
    
                dt.Columns.Add("Col1", typeof(Guid));
                dt.Columns.Add("Col2", typeof(Guid));
                dt.Columns.Add("Col3", typeof(Guid));
    
                while (dt.Rows.Count < 10)
                    dt.Rows.Add(new object[] { Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid() });
    
                this.GridView1.DataSource = dt;
                this.GridView1.DataBind();
            }
        }
    
        public override void VerifyRenderingInServerForm(Control control)
        {
            //base.VerifyRenderingInServerForm(control);
        }
    
        protected void Button1_Click(object sender, EventArgs e)
        {
            ExportToExcel("application/vnd.ms-excel", "下载信息.xls");
        }
    
        public void ExportToExcel(string FileType, string FileName)
        {
            Response.Charset = "GB2312";
            Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
            Response.AppendHeader("Content-Disposition", "attachment;filename=" +
                HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8).ToString());
            Response.ContentType = FileType;            //MIME类型
            this.EnableViewState = false;               //设置页面的请求状态
            System.IO.StringWriter tw = new System.IO.StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(tw); //以HTML结构的字符流
            GridView1.RenderControl(hw);
            Response.Output.Write(tw.ToString());       //将字符串写入文本流
            Response.Flush();                           //缓冲流输出
            Response.End();
        }
    </script>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title>无标题页</title>
    </head>
    <body>
        <form id="form1" runat="server">
        <asp:GridView ID="GridView1" runat="server">
        </asp:GridView>
        <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
        </form>
    </body>
    </html>
    


    知识改变命运,奋斗成就人生!
    2009年12月4日 1:57
    版主
  • 请注意我的问题,我是先倒出来一个中文名称的Excel文件。是正常的。

    打开这个文件,里面的工作表名称变成了乱码:%e4%b8%8b%e8%bd%bd%e4%bf%a1%e6%81%af[1].xls

    。。。。。。。。。。
    2009年12月4日 2:20