简体   繁体   English

在PHP中将CSV导出为Excel

[英]Exporting CSV to excel in PHP

I made a CSV as an example: 我以CSV为例:

Type, जिल्ला शिक्षा कार्यालय डडेलधुरा,NGOI,NGO Request,21,0,0 Response, 4,0,0

and it has utf-8 characters and i want to export it to excel so i posted it and to export it to excel and after referring to several questions on stackoverflow i did as follow: 并且它具有utf-8字符,我想将其导出到excel,所以我将其发布并导出到excel,并在参考了关于stackoverflow的几个问题后做了如下操作:

header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header("Content-Type: text/csv; charset=utf-8");
header('Content-Disposition: attachment; filename=file.csv');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
print $_POST['csv_data'];exit;

the csv is exported to excel nicely but character encoding in not converted and shows something like this: जिलà¥à¤²à¤¾ शिकà¥à¤·à¤¾ कारà¥à¤¯à¤¾à¤²à¤¯ डडेलधà¥à¤°à¤¾ and when i add csv可以很好地导出到excel,但是字符编码没有转换,并且显示如下内容: जिलà¥à¤²à¤¾ शिकà¥à¤·à¤¾ कारà¥à¤¯à¤¾à¤²à¤¯ डडेलधà¥à¤°à¤¾当我加上जिलà¥à¤²à¤¾ शिकà¥à¤·à¤¾ कारà¥à¤¯à¤¾à¤²à¤¯ डडेलधà¥à¤°à¤¾

echo "\xEF\xBB\xBF";

the character encoding is converted but the data appears in one column like this: 字符编码已转换,但数据显示在这样的一列中:

Type, जिल्ला शिक्षा कार्यालय डडेलधुरा,NGOI,NGO
Request,21,0,0
Response, 4,0,0

UTF8 + CSV + Excel is known to be a problematic combination. UTF8 + CSV + Excel被认为是一个有问题的组合。 Excel just isn't very good at importing CSV. Excel只是不能很好地导入CSV。

One thing you should try is to add a UTF8 BOM character at the start of your CSV file; 您应该尝试的一件事是在CSV文件的开头添加UTF8 BOM字符 that might help Excel work out what to do with it. 这可能会帮助Excel找出如何处理它。

I'm optimistic that will help, but if it doesn't, you may have to re-think using CSV for this. 我很乐意为您提供帮助,但如果没有帮助,您可能需要重新考虑使用CSV进行此操作。

Other options you could use instead of CSV would include XML, and creating an actual Excel file from within PHP (there are a number of libraries available which can do this, the best one being PHPExcel ). 您可以使用其他代替CSV的选项包括XML,然后从PHP内创建一个实际的Excel文件(有许多可用的库可以做到这一点,最好的是PHPExcel )。

Hope that helps. 希望能有所帮助。

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

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