• 如何解决ASP.NET导出Excel中文乱码的问题
  • 发布于 2个月前
  • 311 热度
    1 评论
  • 池子
  • 0 粉丝 14 篇博客
  •   

我现在有一个用.NET开发的投资申请管理系统,用户在导出Excel时会出现中文乱码的现象,如下图:

导出Excel的代码如下:

       protected void btnExport_Click(object sender, EventArgs e)
        {
            try
            {
                IEnumerable<F_GetAuthorizedListForInvestmentListResult> iEnum4Export = InvestmentBLL.GetAuthorizedForCashPlanApplicationList(GetDynamicConditions(), TypeHelper.SafeInt(WebHelper.GetCurrentUser().EmployeNumber, 0), this.Page.User.Identity.Name, (IsFromHQ > 0 ? WebHelper.FunctionID_View : WebHelper.FunctionID_BranchView), (IsFromHQ > 0 ? WebHelper.MyAppKey : WebHelper.MyBranchAppKey), 16);
                if (iEnum4Export != null) { 
                    string xlsDirectory = WebHelper.GetExcelDir();
                    string fileName = "InvestmentList-" + System.DateTime.Now.ToString("yyyy-MM-dd HHmmss") + ".xls";
                    if (!Directory.Exists(xlsDirectory))
                        Directory.CreateDirectory(xlsDirectory);
                    if (System.IO.File.Exists(Path.Combine(xlsDirectory, fileName)))
                        System.IO.File.Delete(Path.Combine(xlsDirectory, fileName));
                    AppendToFile(Path.Combine(xlsDirectory, fileName), GetExportHeadLine());
                    foreach (F_GetAuthorizedListForInvestmentListResult fInvestment in iEnum4Export)
                    {
                        AppendToFile(Path.Combine(xlsDirectory, fileName), GetExportContent(fInvestment));
                    }

                    this.Response.Redirect("Excels/" + fileName);
                }
            }
            catch (Exception ex)
            {
                LogService.Write(ex.StackTrace + ex.Message);
                WebHelper.ShowAlert("导出工作流设置出错,错误信息为:" + ex.Message, "DownloadTemplate");
            }
        }

有谁遇到过类似的导出Excel中文乱码的问题吗?要怎么解决?

用户评论
  • 刘棕刃
  • 导出Excel中文乱码的问题一般是和你的编码问题有关,建议在this.Response.Redirect("Excels/"+fileName)这句话前面加入如下一段代码:

    Response.Charset = "GB2312";
    Response.ClearContent();
    Response.Write("<meta http-equiv=Content-Type; content=text/html;charset=GB2312>");       
    Response.Clear();               
    Response.AddHeader("content-disposition", "attachment; filename="+fileName);
    Response.ContentType = "application/excel"; 

    如果GB2312编码无效,可以试着换成UTF-8,根据经验,如果服务器用的是英文环境的建议使用GB2312,如果服务器是中文环境的,建议使用UTF-8

    Response.Charset = "UTF-8";//添加编码格式 
    Response.ClearContent(); 
    Response.Clear(); 
    Response.ContentEncoding = System.Text.Encoding.UTF8;//表格内容添加编码格式 
    Response.HeaderEncoding = System.Text.Encoding.UTF8;//表头添加编码格式 

  • 2018/12/17 13:29:00 [ 0 ] [ 0 ] 回复