简体   繁体   English

CSV文件无法在Excel中正确加载

[英]CSV file not loading correctly in Excel

I've seen a couple of similar questions but have not had one that answers my issue. 我见过几个类似的问题,但还没有一个回答我的问题。

I have an export to CSV button which exports results from my database to CSV. 我有一个“导出到CSV”按钮,可将结果从数据库导出到CSV。

I don't want to save the file, but I just want to use headers to export the echo content to a file which should then be opened in Excel (or similar product). 我不想保存文件,但是我只想使用标题将回显内容导出到文件,然后应在Excel(或类似产品)中打开该文件。

All works fine but Excel does not appear to separate the values, but rather shows all rows in 1 row with the commas intact. 一切正常,但是Excel似乎没有将值分开,而是将所有行显示为1行且逗号完整。 I found a solution elsewhere where I should add "sep=,\\r\\n" to the first line to tell Excel to use commas as the delimiter, which then makes it work great; 我在其他地方找到了一种解决方案,应该在第一行中添加“ sep =,\\ r \\ n”,以告诉Excel使用逗号作为分隔符,然后使其工作得很好。 but, in other products it now shows the sep=, on the first line and continues with the remaining of the output. 但是,在其他产品中,它现在在第一行显示sep =,并继续输出其余内容。

Here is the code I'm using: 这是我正在使用的代码:

 header("Expires: 0");
 header("Cache-control: private");
 header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
 header("Content-Description: File Transfer");
 header("Content-Type: application/vnd.ms-excel");
 header("Content-disposition: attachment; filename=export.csv");
 echo "sep=,\r\n"; // This makes it work in excel but fails in other products such as openoffice
 echo "this,is,just,a,test\r\n";
 exit;

As Mark Baker suggested, as the dilimeter is set by locale settings, I changed it to ; 正如马克·贝克(Mark Ba​​ker)所建议的那样,由于该视差是由区域设置来设置的,因此我将其更改为; and it worked like a charm :) Thank you! 它就像一个魅力:)谢谢!

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

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