在ASP.NET中导出到excel时,中文字符变得不可读

时间:2014-04-01 03:01:55

标签: asp.net-mvc excel

public class HomeController : Controller
{        
    static List<User> GetUsers()
    {
        List<User> list = new List<User>() { 
        new User{Id=1,Name="张三"},
        new User{Id=2,Name="lisi"},
        new User{Id=3,Name="wangwu"}
        };
        return list;
    }
    public void SaveToExcel()
    {
        StringBuilder sb = new StringBuilder();
        sb.Append("id").Append("\t");
        sb.Append("name").Append("\n");
        List<User> list = GetUsers();
        foreach (var item in list)
        {
            sb.Append(item.Id).Append("\t");
            sb.Append(item.Name).Append("\n");
        }
        Response.Clear();
        Response.Buffer = true;
        Response.Charset = "UTF-8";
        Response.ContentEncoding = Encoding.UTF8;
        Response.ContentType = "application/ms-excel";
        Response.AppendHeader("Content-Disposition", "attachment; filename=card.xls");
        Response.Write(sb.ToString());
        Response.End();
    }

中文字符显示为&#34; ????&#34;在excel。

2 个答案:

答案 0 :(得分:0)

您应该使用Microsoft.Office.Interop.Excel或第三方库(如Open XML)来编写Excel,可以在此处找到更多信息:

How to Create Excel file in ASP.NET C#

答案 1 :(得分:0)

您可以使用Response.ContentEncoding = Encoding.Default; 您的默认字符集应为UTF-8