.Net C#MVC中打开下载的excel文件后,文件名更改
我想在我的C#.Net MVC应用程序中导出数据为Excel。 我在Actionresult
使用了return file()
。 该文件已成功返回并下载。
但打开文件时出现错误,打开文件名时会发生变化。 下载的文件名是ExportFilterCRMdoctorRequest.xls
但打开后更改为Book1
。 导出文件的代码:
public ActionResult ExportFilterCRMdoctorRequest() { var stream = new MemoryStream(); var serializer = new XmlSerializer(typeof(List<CDRFilterCRMDoctorRequest>)); //We load the data List<CDRFilterCRMDoctorRequest> data = (List<CDRFilterCRMDoctorRequest>)Session["filterCRMRequestList"]; //Retriving data from Session //We turn it into an XML and save it in the memory serializer.Serialize(stream, data); stream.Position = 0; //We return the XML from the memory as a .xls file return File(stream, "application/vnd.ms-excel", "ExportFilterCRMdoctorRequest.xls"); }
这被称为延伸强化 。 执行步骤以避免此错误。
- 打开您的registry(开始 – >运行 – > regedit.exe)导航到
- HKEY_CURRENT_USER \ SOFTWARE \ MICROSOFT \ OFFICE \ 12.0 \ EXCEL \ SECURITY
- 右键单击右边的窗口,selectNew – > DWORD Type
- “ExtensionHardening”作为名称(不带引号)
- 确认数据的值为“0”
注意
在使用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"); }