在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
最近的项目中需要导出Excel 表格,Excel名称是中文的,在IE中下载老是出现中文名称乱码问题,设置 Respone Encoding 无果,最后找到解决方案如下: public static string ToHexString(string s) { char[] chars = s.ToCharArray(); StringBuilder builder = new StringBuilder(); for (int index = 0; index < chars.Length; index++) { bool needToEncode = NeedToEncode(chars[index]); if (needToEncode) { string encodedString = ToHexString(chars[index]); builder.Append(encodedString); } else { builder.Append(chars[index]); } } return builder.ToString(); } /// <summary> /// Determines if the character needs to be encoded. /// </summary> /// <param name="chr"></param> /// <returns></returns> private static bool NeedToEncode(char chr) { string reservedChars = "$-_.+!*'(),@=&"; if (chr > 127) return true; if (char.IsLetterOrDigit(chr) || reservedChars.IndexOf(chr) >= 0) return false; return true; } /// <summary> /// Encodes a non-US-ASCII character. /// </summary> /// <param name="chr"></param> /// <returns></returns> private static string ToHexString(char chr) { UTF8Encoding utf8 = new UTF8Encoding(); byte[] encodedBytes = utf8.GetBytes(chr.ToString()); StringBuilder builder = new StringBuilder(); for (int index = 0; index < encodedBytes.Length; index++) { builder.AppendFormat("%{0}", Convert.ToString(encodedBytes[index], 16)); } return builder.ToString(); }
使用是,只需调用: //...... string downloadName = ToHexString("中文名称"); //......
|
请发表评论