Utf 8 excel php

To quote a Microsoft support engineer,

Excel for Mac does not currently support UTF-8

Update, 2017: This is true of all versions of Microsoft Excel for Mac before Office 2016. Newer versions (from Office 365) do now support UTF-8.

In order to output UTF-8 content that Excel both on Windows and OS X will be able to successfully read, you will need to do two things:

  1. Make sure that you convert your UTF-8 CSV text to UTF-16LE

    mb_convert_encoding($csv, 'UTF-16LE', 'UTF-8');
    
  2. Make sure that you add the UTF-16LE byte order mark to the start of the file

    chr(255) . chr(254)
    

The next problem that appears only with Excel on OS X (but not Windows) will be when viewing a CSV file with comma separated values, Excel will render rows only with one row and all of the text along with the commas in the first row.

The way to avoid this is to use tabs as your separated value.

I used this function from the PHP comments (using tabs «t» instead of commas) and it worked perfectly on OS X and Windows Excel.

Note that to fix an issue with an empty column as the end of a row, that I did have to change the line of code that says:

    $field_cnt = count($fields);

to

    $field_cnt = count($fields)-1;

As some of the other comments on this page say, other spreadsheet apps like OpenOffice Calc, Apple’s own Numbers and Google Doc’s Spreadsheet have no issues with UTF-8 files with commas.

See the table in this question for what works and doesn’t work for Unicode CSV files in Excel


As a side note, I might add that if you are using Composer, you should have a look at adding LeagueCsv to your requires. LeagueCsv has a really nice API for building CSV files.

To use LeagueCsv with this method of creating CSV files, check out this example

ob_start();

echo 'Désçàui';

header("Content-Type:   application/vnd.ms-excel; charset=utf-8");
header("Content-type:   application/x-msexcel; charset=utf-8");
header("Content-Disposition: attachment; filename=Test.xls"); 
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false); 

ob_end_flush();

What I’m getting in the excel file is Désçàui

However, I do get Désçàui when I try

ob_start();
echo 'Désçàui';
header("Content-Type:   text/html; charset=utf-8");
ob_end_flush();

Any help experts?

PS. The file is saved in DW with Title/Encoding Unicode(Utf-8).

pnuts's user avatar

pnuts

58k11 gold badges85 silver badges137 bronze badges

asked Mar 20, 2011 at 11:21

Jeremy Roy's user avatar

3

Source http://www.mwasif.com/2007/5/download-data-csv-using-php/

Solution worked for me

Danish Zahur said,

October 7, 2009 @ 7:23 pm

If your contents are in UTF-8 format, then no need to convert encoding. Just start your file/output stream with UTF-8 BOM after headers.

echo pack("CCC",0xef,0xbb,0xbf);

And header should contain encoding UTF-8

header( "Content-type: application/vnd.ms-excel; charset=UTF-8" );

It will work like charm because Excel will recognize file charset with BOM bytes.

nobug's user avatar

nobug

1721 silver badge7 bronze badges

answered May 12, 2011 at 10:43

Asif's user avatar

AsifAsif

2812 silver badges2 bronze badges

3

I’m not sure, but it may be that excel can not handle utf8(may depend on the version). But it can handle utf16, so try converting the charset.
This works for me(in excel2002):

echo mb_convert_encoding('Désçàui','utf-16','utf-8');

answered Mar 20, 2011 at 11:48

Dr.Molle's user avatar

Dr.MolleDr.Molle

116k16 gold badges194 silver badges201 bronze badges

2

I don’t know how you’re generating the excel file. But, if you’re doing it from an HTML output, you can just add the following at the begining:

<meta http-equiv="content-type" content="application/xhtml+xml; charset=UTF-8" />

Regards

answered Apr 17, 2012 at 23:10

gonetil's user avatar

gonetilgonetil

2012 silver badges2 bronze badges

0

This UTF-8 BOM line of code made my UTF-8 chars work fine:

 header("Content-type: application/vnd.ms-excel");
 header("Content-Disposition: attachment; filename='".$file_name."'");
 header("Pragma: no-cache");
 header("Expires: 0");
 echo "xEFxBBxBF"; //UTF-8 BOM
 echo $out;

answered Mar 28, 2014 at 14:25

Mladen Janjetovic's user avatar

1

Converting utf8 to html-entities worked quite nicely for me :

$str = 'utf-string ...';
if (mb_detect_encoding($str ) == 'UTF-8') {
   $str = mb_convert_encoding($str , "HTML-ENTITIES", "UTF-8");
}

header('Content-type: application/x-msdownload; charset=utf-16');
header('Content-Disposition: attachment; filename=companies.xls');
header('Pragma: no-cache');
header('Expires: 0');

echo $str ; 

answered Apr 22, 2013 at 10:54

Taher's user avatar

TaherTaher

11.8k2 gold badges30 silver badges44 bronze badges

The content-type headers are relevant for the browser only. They have no effect on downloaded files. Once the file is saved, it is up to the application to decide how it treats the data in the file.

The example you show is not a valid Excel file in the first place. When encountering what it must think is a broken file, Excel probably switches to some default processing that assumes windows-1252 or some other single-byte character set.

You would have to give Excel a proper file to open. Alternatively, it may be possible to use the old «Output HTML but save as XLS» trick and specify a UTF-8 encoding in that HTML file.

answered Mar 20, 2011 at 11:40

Unicron's user avatar

UnicronUnicron

7,2151 gold badge25 silver badges19 bronze badges

3

try this

<?php
header("Content-Type: application/vnd.ms-excel");
header('Content-Disposition: attachment; filename="sample.xls"');
echo "
    <html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40">
    <html>
        <head><meta http-equiv="Content-type" content="text/html;charset=utf-8" /></head>
        <body>
";

echo "
    <table>
      <tr>
        <th rowspan="2" nowrap="nowrap">เลขที่บัญชี</th>
        <th rowspan="2" nowrap="nowrap">ชื่อ-สกุล ลูกค้า</th>
        <th rowspan="2" nowrap="nowrap">OS/Balance</th>
        <th rowspan="2" nowrap="nowrap">วันที่</th>
        <th rowspan="2" nowrap="nowrap">เวลา</th>
        <th rowspan="2" nowrap="nowrap">Action Code</th>
        <th rowspan="2" nowrap="nowrap">Amount</th>
        <th colspan="5" nowrap="nowrap">ผลการติดตาม</th>
      </tr>
      <tr>
        <th nowrap="nowrap">ที่อยู่บ้าน</th>
        <th nowrap="nowrap">เบอร์โทรบ้าน</th>
        <th nowrap="nowrap">เบอร์โทรมือถือ</th>
        <th nowrap="nowrap">ที่อยู่ที่ทำงาน</th>
        <th nowrap="nowrap">เบอร์โทรที่ทำงาน</th>
      </tr>
      <tr>
        <td>acc</td>
        <td>name</td>
        <td>balance</td>
        <td>date</td>
        <td>time</td>
        <td>code</td>
        <td>amount</td>
        <td>h-addr</td>
        <td>h-tel</td>
        <td>cell</td>
        <td>w-addr</td>
        <td>w-tel</td>
      </tr>
    </table>
";

echo "</body></html>";

?>

answered Sep 13, 2014 at 11:13

Manee Mana's user avatar

1

Try this:

header('Content-Transfer-Encoding: binary');
header("Content-Type: application/octet-stream"); 
header("Content-Transfer-Encoding: binary"); 
header('Expires: '.gmdate('D, d M Y H:i:s').' GMT'); 
header('Content-Disposition: attachment; filename = "Export '.date("Y-m-d").'.xls"'); 
header('Pragma: no-cache'); 

//these characters will make correct encoding to excel 
echo chr(255).chr(254).iconv("UTF-8", "UTF-16LE//IGNORE", $out); 

answered Dec 13, 2017 at 6:05

EkoDrive's user avatar

Если надо просто выгрузить некую таблицу с сайта как файл excel, то подойдет достаточно простой способ.

Основная идея — excel уже давно умеет сохранять свои документы как html. Ну и самое простое решение — сохраняем любой документ именно так, открываем в текстовом редакторе, смотрим что и как там написано, пытаемся воспроизвести.
Рассмотрим самый банальный пример: (запрос к базе данных не рассматривается… только та часть, которая выгрузит файл, понятный excel’ю.

1. Формируем заголовок:

/*

// раскомментируйте строки ниже, если файл не будет загружаться

header(«Content-Type: application/force-download»);

header(«Content-Type: application/octet-stream»);

header(«Content-Type: application/download»);

*/

//стандартный заголовок, которого обычно хватает

header(‘Content-Type: application/vnd.ms-excel; charset=utf-8’);

header(«Content-Disposition: attachment;filename=».date(«d-m-Y»).«-export.xls»);

header(«Content-Transfer-Encoding: binary «);

2. Теперь можно выводить ранее полученные данные, из MySQL, из файла, еще откуда — не важно. все на ваше усмотрения. Главное НЕ забыть сформировать стандартную HTML шапку под правильную кодировку (например utf-8) что бы в excel корректно отображалась кириллица. И не забываем про то, что кодировка файла скрипта также должна быть такой же.

echo

   <!DOCTYPE html PUBLIC «-//W3C//DTD XHTML 1.0 Transitional//EN» «http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd»>

   <html xmlns=»http://www.w3.org/1999/xhtml» xml:lang=»en» lang=»en»>

<head>

<meta http-equiv=»content-type» content=»text/html; charset=utf-8″ />

<meta name=»author» content=»zabey» />

<title>Demo</title>

</head>

<body>

;

3. И вот формирование самой таблицы, которая откроется в Excel

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

// заголовок таблицы

echo

  <table border=»1″>

<tr>

<th>Колонка 1</th>

<th>Вторая колонка</th>

</tr>

;

while($row = $STH>fetch()){ // формирование тела таблицы. Выберете ваш метод самостоятельно.

echo ‘<tr>

<td>’.$row[‘col1’].‘</td>

<td>’.$row[‘col2’].‘</td>

      </tr>’;

}

echo ‘</table>’;

echo ‘</body></html>’;

// не забываем закрывать таблицу, боди и сам хтмл документ

Код одним блоком внутри (далее).

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

// !заголовок

/*

// раскомментируйте строки ниже, если файл не будет загружаться

header(«Content-Type: application/force-download»);

header(«Content-Type: application/octet-stream»);

header(«Content-Type: application/download»);

*/

//стандартный заголовок, которого обычно хватает

header(‘Content-Type: application/vnd.ms-excel; charset=utf-8’);

header(«Content-Disposition: attachment;filename=».date(«d-m-Y»).«-export.xls»);

header(«Content-Transfer-Encoding: binary «);

// !! Шапка хтмл

echo

   <!DOCTYPE html PUBLIC «-//W3C//DTD XHTML 1.0 Transitional//EN» «http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd»>

   <html xmlns=»http://www.w3.org/1999/xhtml» xml:lang=»en» lang=»en»>

<head>

<meta http-equiv=»content-type» content=»text/html; charset=utf-8″ />

<meta name=»author» content=»zabey» />

<title>Demo</title>

</head>

<body>

;

// !!! Таблица с данными

// заголовок таблицы

echo

  <table border=»1″>

<tr>

<th>Колонка 1</th>

<th>Вторая колонка</th>

</tr>

;

while($row = $STH>fetch()){ // формирование тела таблицы. Выберете ваш метод самостоятельно.

echo ‘<tr>

<td>’.$row[‘col1’].‘</td>

<td>’.$row[‘col2’].‘</td>

      </tr>’;

}

echo ‘</table>’;

echo ‘</body></html>’;

// не забываем закрывать таблицу, боди и сам хтмл документ

Загрузка…

Содержание

  1. PHP generate Excel/CSV file and send as UTF-8
  2. 6 Answers 6
  3. php header excel and utf-8
  4. 8 Answers 8
  5. Solution worked for me
  6. Is there any way I can ease Excel’s UTF-8 handling using PHP?
  7. php header excel и utf-8
  8. 8 ответов
  9. Решение работало для меня
  10. PHP to MySql to CSV to Excel UTF-8

PHP generate Excel/CSV file and send as UTF-8

I’m retrieving data from my Postgres DB in UTF-8. The db and the client_connection settings are in UTF-8.

Then I send 2 headers to the visitor:

and start outputting plain text data in a CSV-manner. This will open as a simple Excel file on the visitors desktop.

Works fine, untill special characters like é, è etc are encountered.

I tried changing my client_encoding while retrieving the data from the db to latin-1, which works in most cases but not for all chars. So that is not a solution.

How could I send the outputted file as UTF-8? I don’t think converting the data from the db to latin-1 is possible, since the char seems unknown in latin-1 . so I need Excel to treat the file as UTF-8

6 Answers 6

I’d look into using the PHPExcel engine. It uses UTF-8 as default and it can generate a whole list of spreadsheet file types (Excel, OpenOffice, CSV, etc.).

I would recommend not sending plain-text and masquerading it as Excel. XLS files are typically binary, and while binary isn’t required, the official Excel method of using non-binary data is to format it as XML.

You mention «CSV» in the title, but nothing about your problem includes anything related to CSV. I bring this up because I believe that you should actually change your tabs to commas, and then you could simply output a standard .csv file, which is read by Excel still but doesn’t rely on undocumented or unstable functionality.

If you truly want to send application/msexcel , then you should use a real Excel library, because currently, you are not creating a real Excel file.

Источник

php header excel and utf-8

What I’m getting in the excel file is Désçà ui

However, I do get Désçàui when I try

Any help experts?

PS. The file is saved in DW with Title/Encoding Unicode(Utf-8).

8 Answers 8

Solution worked for me

Danish Zahur said,

October 7, 2009 @ 7:23 pm

If your contents are in UTF-8 format, then no need to convert encoding. Just start your file/output stream with UTF-8 BOM after headers.

And header should contain encoding UTF-8

header( «Content-type: application/vnd.ms-excel; charset=UTF-8» );

It will work like charm because Excel will recognize file charset with BOM bytes.

I’m not sure, but it may be that excel can not handle utf8(may depend on the version). But it can handle utf16, so try converting the charset. This works for me(in excel2002):

I don’t know how you’re generating the excel file. But, if you’re doing it from an HTML output, you can just add the following at the begining:

This UTF-8 BOM line of code made my UTF-8 chars work fine:

Converting utf8 to html-entities worked quite nicely for me :

The content-type headers are relevant for the browser only. They have no effect on downloaded files. Once the file is saved, it is up to the application to decide how it treats the data in the file.

The example you show is not a valid Excel file in the first place. When encountering what it must think is a broken file, Excel probably switches to some default processing that assumes windows-1252 or some other single-byte character set.

You would have to give Excel a proper file to open. Alternatively, it may be possible to use the old «Output HTML but save as XLS» trick and specify a UTF-8 encoding in that HTML file.

Источник

Is there any way I can ease Excel’s UTF-8 handling using PHP?

I have been having some very peculiar UTF-8 behaviour from a couple of scripts that import and export information to/from a database via CSV files, especially the way Excel handles them.

The scripts themselves are not particularly complex, and I believe I’m setting the encoding correctly (for the sake of brevity, I have excluded error handling and character escaping code):

Import

Export

To my eye, both of these scripts work fine, no problems so far. However, when I open and work on the exported CSV file in Excel, this is where the interesting stuff begins.

The information in the database contains foreign latin characters like é and Ü . These store correctly (the MySQL database encoding is utf8_unicode_ci ), still no problems yet.

However, only two of the three scenarios work correctly. But guess what, the one that doesn’t work (Scenario Two) is the one I need to work. isn’t that always the way?

Scenario One

I export a CSV file, and then re-import it immediately. I never open or modify the file in any way.

Unfortunately, this is a pointless exercise. It does work, though.

Scenario Two

I export a CSV file, open it, modify the contents, save, and then re-import.

Interesting note: when I choose «Save» from the dialogue menu in Excel, it saves as a «Unicode Text» file instead of overwriting the CSV file. This new file still opens in Excel, but the data is corrupt. I need to choose «Save As. » and select «Comma Separated Values» from the file type menu. I have also attempted to choose UTF-8 from the encoding menu on this step.

The problem with this scenario lies in the foreign characters: as soon as the import script reaches one of them, it simply stops writing that field to the database. No corrupt characters †. No little question marks � . Simply, nothing. However, the rest of the data in that row of the CSV is written fine.

Scenario Three

I export a CSV file, open it, modify the contents, save, open in a text editor, re-save with UTF-8 encoding, then re-import.

Hurrah, it works! However, I can’t expect the users of this system to play about with text editors and encodings — they should be able to export > edit > save > import seamlessly.

My Thoughts on What Is Going Wrong™

  1. Something in one of my scripts (probably the import) is not handling the encoding correctly.
  2. Something in one of my scripts (probably the export) is not correctly creating a CSV file, hence the Unicode Text file type on the Save dialogue.
  3. Excel just really doesn’t like UTF-8 files, and there’s nothing I can do.

Please tell me the fault here lies with me, and there’s a way I can get around this!

Источник

То, что я получаю в файле excel, DÃsçà ui

Тем не менее, я получаю Désçàui, когда я пытаюсь

Любые эксперты помощи?

PS. Файл сохраняется в DW с типом/кодировкой Unicode (Utf-8).

8 ответов

Я не уверен, но может быть, что excel не может обрабатывать utf8 (может зависеть от версии). Но он может работать с utf16, поэтому попробуйте преобразовать кодировку. Это работает для меня (в excel2002):

Решение работало для меня

Датский Захур сказал:

7 октября 2009 года, 7:23 вечера

Если ваше содержимое находится в формате UTF-8, тогда нет необходимости конвертировать кодировку. Просто запустите свой файловый/выходной поток с помощью спецификации UTF-8 после заголовков.

И заголовок должен содержать кодировку UTF-8

header( «Content-type: application/vnd.ms-excel; charset=UTF-8» );

Он будет работать как шарм, потому что Excel распознает кодировку файлов с байтами спецификации.

Я не знаю, как вы создаете файл excel. Но, если вы делаете это из вывода HTML, вы можете просто добавить следующее в начале:

Эта строка кода спецификации UTF-8 сделала мои символы UTF-8 прекрасными:

Преобразование utf8 в html-объекты работало для меня довольно хорошо:

Заголовки content-type относятся только к браузеру. Они не влияют на загруженные файлы. После сохранения файла приложение может решить, как он обрабатывает данные в файле.

Приведенный вами пример не является действительным файлом Excel в первую очередь. Когда он сталкивается с тем, что он должен считать сломанным файлом, Excel, вероятно, переключается на некоторую обработку по умолчанию, которая предполагает windows-1252 или какой-то другой однобайтовый набор символов.

Вам нужно будет предоставить Excel подходящий файл для открытия. В качестве альтернативы можно использовать старый трюк «Выход HTML, но сохранить как XLS» и указать кодировку UTF-8 в этом HTML файле.

Источник

PHP to MySql to CSV to Excel UTF-8

I know this has been discussed several times but yet I’m getting crazy dealing with this problem. I have a form with a submit.php action. At first I didn’t change anything about the charsets, I didn’t use any utf8 header information.. The result was that I could read all the ä,ö,ü etc correctly inside the database. Now exporting them to .csv and importing them to Excel as UTF-8 charset (also tested all the others) results in an incorrect charset.

Now what I tried:

MySQL: I dropped my database and created a new one:

I changed my my.cnf and restarted my sql server:

If I connect to my db via bash I receive the following output:

require.sql is simply a

And again I’m unable to import it as a csv into Excel no matter if I choose UTF-8 or anything else. It’s always giving me some crypto..

Hopefully someone got a hint what might went wrong here..

E: TextMate is giving me a correct output so it seems that the conversion actually worked and it’s and Excel issue? Using Microsoft Office 2011.

E2: Also tried the same stuff with latin1 — same issue, cannot import special characters into excel without breaking them. Any hint or workaround?

E3: I found a workaround which is working with the Excel Import feature but not with double clicking the .csv.

Now I’m able to import the csv into excel using Windows(ANSI). Still annoying to have to use this feature instead of doubleclicking. Also I really don’t get why UTF8 isn’t working, not even with the import feature, BOM added and the complete database in UTF8.

Comma separation turned out to be a mess as well. 1. Concat_WS works only partly because it’s adding a stupid concat_ws(..) header to the .csv file. Also «file test.csv» doesn’t give me a «comma separated». This means even tho everything is separated by commas Excel won’t notice it using double click. 2. sed/awk: Found some code snippets but all of them were separating the table very badly. E.g. colum street «streetname number» remained a ‘streetname’,’number’ which made 2 colums out of one and the table was screwed.

So it seems to me that Excel can only open .csv with a double click which a) Are encoded with ISO-8859-1 (and only under windows because standard mac charset is Macintosh) b) File having the attribute «comma separated». This means if I create a .csv through Excel itself the output of

while a iconv changed charset with RegEx used for adding commas would look like:

Pretty weird behaviour — maybe someone got a working solution.

Источник

  • gordon_shamway

БД в UTF-8, файл в UTF-8.
Сsv тоже в UTF-8, а EXCEL пытается открыть его в ANSI.
Что делать?

global $begin_date;
	global $end_date;
	
	header("Content-type: text/csv");
	header("Content-Transfer-Encoding: UTF-8");
	header("Content-Disposition: attachment; filename=[$begin_date][$end_date].csv");
	header("Pragma: no-cache");
	header("Expires: 0");
	
	//$result = $mysqli->query($sql);
	echo "sip;clid;record;call_sec;call_min;y;m;d;h;mn";
	//while ($line = $result->fetch_assoc()) {
		//$datetime = date_timestamp_get(date_create($line['datetime']));
		//echo "n";
	//}
	exit;


  • Вопрос задан

    более трёх лет назад

  • 1112 просмотров

Пригласить эксперта

header("Content-type: text/csv; charset=utf-8");
это как вариант.

и вы уверены что эксель именно в ansi пытается открыть а не в win-1251? или koi8-r? возможно он пытается подстроить файл под стандартную кодировку ОС.

В старых экселях была галочка «подтверждать преобразование при открытии». После её включения, при открытии csv файла появлялся диалог открытия с выбором параметров, в том числе и кодировки.
В новых версиях можно воспользоваться «Мастером импорта текста» https://support.office.com/ru-ru/article/мастер-им…


  • Показать ещё
    Загружается…

14 апр. 2023, в 19:10

25000 руб./за проект

14 апр. 2023, в 19:05

500 руб./за проект

14 апр. 2023, в 18:58

10000 руб./за проект

Минуточку внимания

Like this post? Please share to your friends:
  • Utf 8 encoding microsoft word
  • Utf 8 encoding for excel
  • Utf 8 encoding csv excel
  • Using you and me in a sentence for each word
  • Using wrong word to describe