将CSV文件导出到Excel 2007

我有一些代码将数据结果作为CSV发送给用户。 这对Excel 2013工作正常,但在Excel 2007中,它不会拆分成列,而是作为只插入到一列中的数据。

有没有办法告诉Excel如何拆分文本(它被分隔)? 这是我的代码:

public async Task ExcelResultList(int id) { var asString = await Resolver.Resolve<IHandoutManager>().GetResultListAsStringAsync(id); var handout = await Resolver.Resolve<IHandoutManager>().GetHandout(id); var filename = string.Format("{0} registrations - {1:yyyy-MM-dd}.csv", handout.Name, DateTime.Now); var contenttype = "application/csv"; Response.Clear(); Response.ContentType = contenttype; Response.AddHeader("content-disposition", "attachment;filename=" + filename); Response.Cache.SetCacheability(HttpCacheability.NoCache); Response.ContentEncoding = Encoding.Unicode; Response.Write(asString); Response.End(); } 

为了确保您使用的是正确的ListSeparator(“,”或“;”),请使用此选项

System.Globalization.CultureInfo.CurrentCulture.TextInfo.ListSeparator

但是既然你只能访问服务器端,那么你可以在你的任何页面中包含这个JavaScript,

 function getListSeparator() { var list = ['a', 'b'], str; if (list.toLocaleString) { str = list.toLocaleString(); if (str.indexOf(';') > 0 && str.indexOf(',') == -1) { return ';'; } } return ','; } 

关键在于使用客户端系统列表分隔符的toLocaleString方法

您可以使用JavaScript获取列表分隔符并将其设置为一个cookie,然后您可以从服务器检测到该cookie以根据需要生成该文件

而且你也可以尝试改变内容types

 application/vnd.openxmlformats-officedocument.spreadsheetml.sheet 

要么

 application/vnd.ms-excel