简体   繁体   中英

excel utf-8 csv export and the separator

So I did this (I use Drupal 6):

  while(@ob_end_clean());
  drupal_set_header("Content-type: text/csv;");
  drupal_set_header("Cache-Control: no-store, no-cache");
  drupal_set_header("Content-Disposition: attachment; filename=translations.csv");
  print chr(255) . chr(254) . mb_convert_encoding($output, 'UTF-16LE', 'UTF-8');
  exit;

To export a CSV of utf-8 characters. And the utf-8 characters would display properly when I import into excel.

The problem is, excel would not parse the separators, ie, the commas would all display in one column instead of being used as a separator on file open.

Is there a way to make it so that when I open it, the commas will be used as a separator?

A line in the csv goes the following:

$output .= '"'.str_replace('"', '""', $id).'","'.str_replace('"', '""', $source).'","'.str_replace('"', '""', $translation) . '"';

I tried using tabs \\t instead of commas as separators but the same thing would happen, ie. the tabs will not be used as separator on file open

If your using Excel 2007 then if you open Excel first, then you can go to the Data tab and then select From Text

Select your .csv file in the explorer browser and then the text wizard should appear. This gives you more steps and options to control what it is looking for with regards to breaking up the columns etc.

Older version of Excel also support it but I can't be certain its in the same place, I think it is though.

Try that wizard and see how if it sorts your problem.

To use comma as default CSV separator, one needs to change corresponding Windows Regional Settings option:

Go to the Control Panel --> Regional and Language Options (or Date, Time and Regional Options --> Regional and Language Option on some machines) --> click the Customize button. In the dialog box that opens you will see and option for " List separator " in which you can change the comma to a different character --> click Apply then Ok and then Apply again.

Please note the following:

  1. This setting is used for BOTH CSV import and export by default.
  2. You should open CSV files using File > Open , NOT Data > Import External Data > Import Data... , or simply double-click any CSV in Explorer, and it will be opened in Excel with default separator applied.

Read more:

For Unicode support from Excel with x-separated-values, use tab-separated UTF-16 Little-Endian (what Excel generates when you Save As... > Unicode Text (*.txt) ).

If you don't, you get issues like what you're experiencing.

See: Excel and Unicode

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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