将CSV文件导出到Excel 2007

时间:2013-09-05 11:36:39

标签: c# excel asp.net-mvc-4 csv

我有一些代码用于将数据结果作为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();
    }

1 个答案:

答案 0 :(得分:2)

要确保使用正确的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以根据需要生成文件

您还尝试将内容类型更改为

application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

application/vnd.ms-excel