简体   繁体   English

将CSV文件导出到Excel 2007

[英]Export CSV file to Excel 2007

I have some code for sending a data result to the user as CSV. 我有一些代码可以将数据结果作为CSV发送给用户。 This works fine with Excel 2013 but in Excel 2007, it won't split into columns, but rather as data inserted into only one column. 这在Excel 2013上工作正常,但在Excel 2007中,它不会拆分为列,而是将数据仅插入一列。

Is there a way of telling Excel how to split the text (it's separated by ; ) ? 有没有一种方法告诉Excel如何拆分文本(用;分隔)? Here is my code: 这是我的代码:

    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();
    }

To make sure that you are using the correct ListSeparator ("," or ";") use this 为确保使用正确的ListSeparator(“,”或“;”),请使用

System.Globalization.CultureInfo.CurrentCulture.TextInfo.ListSeparator System.Globalization.CultureInfo.CurrentCulture.TextInfo.ListSeparator

But since you only have access to the server side, then you can include this javascript in any of your pages, 但是,由于您只能访问服务器端,因此可以在任何页面中包含此javascript,

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

The key is in the toLocaleString method that uses the system list separator of the client side 关键在使用客户端的系统列表分隔符的toLocaleString方法中

You could use JavaScript to get the list separator and set it in a cookie which you could then detect from your server to generate the file as needed 您可以使用JavaScript获取列表分隔符并将其设置在cookie中,然后可以从服务器中检测到该cookie以根据需要生成文件

And also have you try changing the contenttype to 而且您是否尝试将contenttype更改为

application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

or 要么

application/vnd.ms-excel

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM