我有一个MVC应用程序,它会将一些数据下载到Excel文件中。我很难搞清楚正确的应用程序类型应该是什么。
在下面的代码中,您可以看到我尝试过的所有不同的应用程序类型,以及我发现的唯一一个未被注释的应用程序类型。我必须使用.csv文件扩展名,我宁愿使用.xls或.xlsx。
当我尝试使用.xls扩展名的任何内容时,它将返回但是每一行都将被放置在第一个单元格中,因为它们被添加到每个列中。如果我使用.xlsx扩展名,我会收到一个错误,即它是错误的扩展类型,然后根本没有显示任何内容。
将.csv扩展名与vnd.ms.excel类型一起使用可以正常工作。只是文件扩展名是.csv而不是.xls或.xlsx,这是首选。知道为什么.xls或.xlsx无效吗?
public FileResult ExcelDownload()
{
List<Employee> lstEmployee = new List<Employee>();
try
{
lstEmployee = DataManager.GetData();
}
catch (Exception ex)
{
logger.Error("Error while getting data. Error: {0} | Trace: {1}", ex.Message, ex.StackTrace);
}
var sbItem = new System.Text.StringBuilder();
if (lstEmployee != null && lstEmployee.Count > 0)
{
logger.Debug("Excel record count: " + lstEmployee.Count);
int rank = 1;
sbItem.AppendLine("Seniority,Co,CityCode,Employee,LastName,FirstName,JobTitle,EmployType,SeniorityDate,LOA,TWA");
foreach (Employee e in lstEmployee)
{
//Add the seniority rank to each employee
e.SeniorityRank = rank;
sbItem.AppendLine(e.SeniorityRank + "," +
e.Co + "," +
e.CityCode + "," +
e.EmployeeNumber + "," +
e.FirstName + "," +
e.LastName + "," +
e.Position + "," +
e.EmploymentType + "," +
string.Format("{0:yyyy/MM/dd}", e.SeniorityDate) + "," +
e.LOA);
rank += 1;
}
}
return File(new System.Text.UTF8Encoding().GetBytes(sbItem.ToString()), "application/vnd.ms-excel", "SeniorityList.csv");
//return new File(sbItem.ToString(), "application/vnd.ms-excel", "SeniorityList.xls");
//return File(new System.Text.UTF8Encoding().GetBytes(sbItem.ToString()), "text/csv", "SeniorityList.csv");
//return File(new System.Text.UTF8Encoding().GetBytes(sbItem.ToString()), "vnd.openxmlformats-officedocument.spreadsheetml.sheet ", "SeniorityList.xlsx");
}