Export CSV for Excel

前端 未结 5 1237
耶瑟儿~
耶瑟儿~ 2020-12-29 16:58

I\'m writing a CSV file in PHP using fputcsv($file, $data). It all works, however I can\'t just open it in Excel but have to import it and specify the encoding

5条回答
  •  温柔的废话
    2020-12-29 17:42

    this is really a mess. You surely can use the sep=; or sep=, or sep=\t or whatever to make Excel aware of a separator used in your CSV. Just put this string at the beginning of your CSV contents. E.g.:

    fwrite($handle, "sep=,\n");
    
    fputcsv($handle,$yourcsvcontent);
    

    This works smoothly. BUT, it doesn't work in combination with a BOM which is required to make Excel aware of UTF-8 in case you need to support special characters or MB respectively.

    In the end to make it bullet-proof you need to read out users locale and set the Separator accordingly, as mentioned above. Put a BOM ("\xEF\xBB\xBF") at the begining of your CSV content, then write the CSV like e.g.: fputcsv($handle, $fields, $user_locale_seperator); where $user_locale_seperator is the separtator you retrieved by checking the user's locale. Not comfortable but it works...

提交回复
热议问题