1 public class HomeController : Controller
2 {
3 static List<User> GetUsers()
4 {
5 List<User> list = new List<User>() {
6 new User{Id=1,Name="张三"},
7 new User{Id=2,Name="lisi"},
8 new User{Id=3,Name="wangwu"}
9 };
10 return list;
11 }
12 public void SaveToExcel()
13 {
14 StringBuilder sb = new StringBuilder();
15 sb.Append("id").Append("\t");
16 sb.Append("name").Append("\n");
17 List<User> list = GetUsers();
18 foreach (var item in list)
19 {
20 sb.Append(item.Id).Append("\t");
21 sb.Append(item.Name).Append("\n");
22 }
23 Response.Clear();
24 Response.Buffer = true;
25 Response.Charset = "UTF-8";
26 Response.ContentEncoding = Encoding.UTF8;
27 Response.ContentType = "application/ms-excel";
28 Response.AppendHeader("Content-Disposition", "attachment; filename=card.xls");
29 Response.Write(sb.ToString());
30 Response.End();
31 }
这个该怎么设置下?谢谢
改成下面这样的:
Response.Charset = "GB2312";//定义输出字符集
Response.ContentEncoding = Encoding.Default;//输出内容的编码为默认编码
我以前做过这方面的东西,这个是一个WinForm的代码,楼主看看会不会有帮助吧。
public void SaveToExcel()
13 {
14 StringBuilder sb = new StringBuilder();
15 sb.Append("id").Append("\t");
16 sb.Append("name").Append("\n");
17 List<User> list = GetUsers();
18 foreach (var item in list)
19 {
20 sb.Append(item.Id).Append("\t");
21 sb.Append(item.Name).Append("\n");
22 }
23 Response.Clear();
24 Response.Buffer = true;
25 Response.Charset = "UTF-8";
26 Response.ContentEncoding = Encoding.UTF8;
27 Response.ContentType = "application/ms-excel";
28 Response.AppendHeader("Content-Disposition", "attachment; filename=card.xls");
29 //加上这句
30 Response.Write("<meta http-equiv=\"content-type\" content=\"application/vnd.ms-excel; charset=utf-8\"/>" + sb.ToString());
31 Response.End();
32 }
给个赏呗!!