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。
答案 0 :(得分:0)
您应该使用Microsoft.Office.Interop.Excel
或第三方库(如Open XML
)来编写Excel,可以在此处找到更多信息:
答案 1 :(得分:0)
您可以使用Response.ContentEncoding = Encoding.Default; 您的默认字符集应为UTF-8