这称为扩展硬化。执行步骤以避免此错误。
- 打开您的注册表(开始 -> 运行 -> regedit.exe)导航到
- HKEY_CURRENT_USER\SOFTWARE\MICROSOFT\OFFICE\12.0\EXCEL\SECURITY
- 右键单击右侧窗口并选择新建 -> DWORD 类型
- “ExtensionHardening”作为名称(不带引号)
- 验证数据的值是否为“0”</li>
笔记
在 XML 中序列化时必须牢记一件事。XML 不是 Excel 的标准格式,它必须将文件作为 XML 数据打开。这意味着当打开文件时,它会发出一些警告,这些警告比其他任何东西都更令人讨厌。
回到你原来的查询:复制你的问题,下面是修复
样本类
public class StudentModel
{
public string Name { get; set; }
public string Address { get; set; }
public string Class { get; set; }
public string Section { get; set; }
}
样本数据
private List<StudentModel> StudentData()
{
List<StudentModel> objstudentmodel = new List<StudentModel>();
objstudentmodel.Add(new StudentModel { Name = "Name1", Class = "1",
Address = "Address1", Section = "A" });
objstudentmodel.Add(new StudentModel { Name = "Name2", Class = "2",
Address = "Address2", Section = "A" });
return objstudentmodel;
}
动作方法
public ActionResult Index()
{
List<StudentModel> objstudent = new List<StudentModel>();
objstudent = StudentData();
StringBuilder sb = new StringBuilder();
sb.Append("<table border='" + "1px" + "'b>");
//code section for creating header column
sb.Append("<tr>");
sb.Append("<td><b><font size=2>NAME</font></b></td>");
sb.Append("<td><b><font size=2>CLASS</font></b></td>");
sb.Append("<td><b><font size=2>ADDRESS</font></b></td>");
sb.Append("<td><b><font size=2>SECTION</font></b></td>");
sb.Append("</tr>");
//code for creating excel data
foreach (StudentModel item in objstudent)
{
sb.Append("<tr>");
sb.Append("<td><font>" + item.Name.ToString() + "</font></td>");
sb.Append("<td><font>" + item.Class.ToString() + "</font></td>");
sb.Append("<td><font>" + item.Address.ToString() + "</font></td>");
sb.Append("<td><font>" + item.Section.ToString() + "</font></td>");
sb.Append("</tr>");
}
sb.Append("</table>");
HttpContext.Response.AddHeader("content-disposition",
"attachment; filename=student_" +
DateTime.Now.Year.ToString() + ".xls");
this.Response.ContentType = "application/vnd.ms-excel";
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(sb.ToString());
return File(buffer, "application/vnd.ms-excel");
}