解决火狐/IE导出Excel文件名为中文时乱码问题

通常导出excel:

string fileName="中文名称";

Response.ContentType = "application/ms-excel";
            Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8) + ".xls");
            Response.ContentEncoding = System.Text.Encoding.UTF7;
            Response.BinaryWrite(File.ReadAllBytes(filePath));

上面代码能够解决IE文件名乱码问题,但解决不了火狐;

同时解决火狐/IE上Excel文件名乱码问题:

string fileName="中文名称";

Response.ContentType = "application/ms-excel";
            Response.AppendHeader("Content-Disposition", "attachment;filename=" +UrlOper.GetToExcelName(m_title) + ".xls");
            Response.ContentEncoding = System.Text.Encoding.UTF7;
            Response.BinaryWrite(File.ReadAllBytes(filePath));

注意上面UrlOper.GetToExcelName(m_title)方法,这是本人封装的方法,它的主要作用是判断浏览器,然后编码中文,之后就不会出现乱码问题了:

/// <summary>
        /// 转换中文excel名称,防止乱码
        /// </summary>
        /// <param name="fileName">中文名称</param>
        /// <returns></returns>
        public static string GetToExcelName(string fileName)
        {
            string UserAgent = HttpContext.Current.Request.ServerVariables["http_user_agent"].ToLower();
            if (UserAgent.IndexOf("firefox") == -1)
                fileName = HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8);
            return fileName;
        }




猜你喜欢

转载自blog.csdn.net/xuwei_net/article/details/6606105
今日推荐