Mysql for excel кодировка

I had the same problem (common problem in databases with spanish language). I wrote this and it worked:

This is a Class that connects with the database and the functions will do whatever you want using mysqli and PHP. In this case, calling this class (require or include), just use the «downloadCsv()» function.

As an example, this would be the «class.php» file:

<?php
class DB{

private $con;

//this constructor connects with the database
public function __construct(){
$this->con = new mysqli("Your_Host","Your_User","Your_Pass","Your_DatabaseName");

if($this->con->connect_errno > 0){
    die('There was a problem [' . $con->connect_error . ']');
    }
}

//create the function that will download a csv file from a mysqli query

public function downloadCsv(){

$count = 0;
$header = "";
$data = "";
//query
$result = $this->con->query("SELECT * FROM Your_TableName");
//count fields
$count = $result->field_count;
//columns names
$names = $result->fetch_fields();
//put column names into header
foreach($names as $value) {
    $header .= $value->name.";";
    }
}
//put rows from your query
while($row = $result->fetch_row())  {
    $line = '';
    foreach($row as $value)       {
        if(!isset($value) || $value == "")  {
            $value = ";"; //in this case, ";" separates columns
    } else {
            $value = str_replace('"', '""', $value);
            $value = '"' . $value . '"' . ";"; //if you change the separator before, change this ";" too
        }
        $line .= $value;
    } //end foreach
    $data .= trim($line)."n";
} //end while
//avoiding problems with data that includes "r"
$data = str_replace("r", "", $data);
//if empty query
if ($data == "") {
    $data = "nno matching records foundn";
}
$count = $result->field_count;

//Download csv file
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=FILENAME.csv");
header("Pragma: no-cache");
header("Expires: 0");
echo $header."n".$data."n";

}
?>

After creating the «class.php» file, in this example, use that function on «download.php» file:

<?php
//call the "class.php" file
require_once 'class.php';
//instantiate DB class
$export = new DB();
//call function
$export->downloadCsv();
?>

After download, open the file with MS Excel.

I hope this help you, I think I wrote it well, I didn’t feel comfortable with the text and code field.

Если нужно быстро и единоразово выгрузить данные из таблицы MySQL в Exel файл, то помогут следующие способы:

1

Экспорт через PHPMyAdmin

В PHPMyAdmin при экспорте можно выбрать формат «CSV for MS Excel»:

Экспорт через PHPMyAdmin

При открытии полученного файла в Excel будет сбита кодировка:

Excel будет сбита кодировка

Чтобы это исправить, нужно открыть csv файл в редакторе типа Notepad++ и изменить кодировку на ANSI:

Notepad++ изменить кодировку на ANSI:

Результат:

2

Экспорт через HTML таблицу

Смысл метода состоит в том чтобы PHP-скриптом сформировать HTML таблицу:

<?php
$dbh = new PDO('mysql:dbname=db_name;host=localhost', 'логин', 'пароль');
$sth = $dbh->prepare("SELECT * FROM `test`");
$sth->execute();
$items = $sth->fetchAll(PDO::FETCH_ASSOC);
?>
		
<table>
	<tr>
		<td>ID</td>
		<td>Категория</td>
		<td>Название</td>
		<td>Описание</td>
	</tr>
	<?php foreach($items as $row): ?>
	<tr>
		<td><?php echo $row['id']; ?></td>
		<td><?php echo $row['category']; ?></td>
		<td><?php echo $row['name']; ?></td>
		<td><?php echo $row['text']; ?></td>
	</tr>
	<?php endforeach; ?>
</table>

PHP

Результат работы скрипта:

Полученную таблицу копируем и вставляем в чистый лист Microsoft Exel:

3

Экспорт через PHPExcel

Третий метод – сформировать xls-файл в библиотеке PHPExcel (PHPExcel.zip).

//spl_autoload_unregister('autoload');
require_once __DIR__ . '/PHPExcel/Classes/PHPExcel.php';
require_once __DIR__ . '/PHPExcel/Classes/PHPExcel/Writer/Excel2007.php';

$xls = new PHPExcel();
$xls->setActiveSheetIndex(0);
$sheet = $xls->getActiveSheet();

// Шапка
$sheet->getStyle("A1:D1")->getFont()->setBold(true);
$sheet->setCellValue("A1", 'ID');
$sheet->setCellValue("B1", 'Категория');
$sheet->setCellValue("C1", 'Название');
$sheet->setCellValue("D1", 'Описание');

// Выборка из БД
$dbh = new PDO('mysql:dbname=db_name;host=localhost', 'логин', 'пароль');
$sth = $dbh->prepare("SELECT * FROM `test`");
$items = $sth->fetch(PDO::FETCH_ASSOC);

$index = 2;
foreach ($items as $row) {
	$sheet->setCellValue("A" . $index, $row['id']);
	$sheet->setCellValue("B" . $index, $row['category']);
	$sheet->setCellValue("C" . $index, $row['name']);
	$sheet->setCellValue("D" . $index, $row['name']);
	$index++;
}

// Отдача файла в браузер
header("Expires: Mon, 1 Apr 1974 05:00:00 GMT");
header("Last-Modified: " . gmdate("D,d M YH:i:s") . " GMT");
header("Cache-Control: no-cache, must-revalidate");
header("Pragma: no-cache");
header("Content-type: application/vnd.ms-excel" );
header("Content-Disposition: attachment; filename=prods.xlsx");
 
$objWriter = new PHPExcel_Writer_Excel2007($xls);
$objWriter->save('php://output'); 

exit(); 

PHP

Результат:

5 / 5 / 3

Регистрация: 19.09.2013

Сообщений: 303

1

01.02.2014, 14:12. Показов 13016. Ответов 6


Студворк — интернет-сервис помощи студентам

Экспортирую таблицу из mysql в «csv для excel», таблица кодировкой utf8, база тоже, столбцы где есть русские буквы имеют сравнение utf8_general_ci (что это такое кстати?), тип таблиц InnoDB. в блокноте все норм отображает, в экселе кракозябры. в экселе в параметрах веб-документа поставил Юникод. что можно сделать?



0



5 / 5 / 3

Регистрация: 19.09.2013

Сообщений: 303

03.02.2014, 14:41

 [ТС]

2

Ребят помогите с кракозябрами. в экселе нормально текст не хочет выводиться. из пхпМайАдмина делаю экспорт, в блокноте норм выводит, в экселе нет



0



813 / 796 / 201

Регистрация: 21.09.2012

Сообщений: 2,656

03.02.2014, 14:48

3

вручную если только изменять с помощью Notepad++ кодировку на cp1251



0



5 / 5 / 3

Регистрация: 19.09.2013

Сообщений: 303

03.02.2014, 14:58

 [ТС]

4

Dolphin, а может тогда лучше базу в cp-1251 перевести, эт поможет? а в соединение с базой вот это написать mysql_query(‘set names utf8’); ?



0



813 / 796 / 201

Регистрация: 21.09.2012

Сообщений: 2,656

03.02.2014, 15:00

5

А нет, сначало переключаешь на показ всеx настроек.

Кракозябры при экспорте в csv

А потом выбираешь кодировку, в которой будет получившийся файл. А именно windows-1251

Кракозябры при экспорте в csv



1



5 / 5 / 3

Регистрация: 19.09.2013

Сообщений: 303

03.02.2014, 15:02

 [ТС]

6

Dolphin, спасибо тебе) работает.



0



1177 / 419 / 106

Регистрация: 31.03.2012

Сообщений: 1,138

03.02.2014, 15:13

7

Здесь обрати внимание на select … into outfile ‘file_name‘ character set chaset_name. Вероятно, стоит указать cp1251
Опоздал



0



I try to export one of MySQL table into excel file but polish letters aren’t displaying correctly
It is displayed:
Bre¶ć, Białoru¶
but should:
Brześć, Białoruś

How can I fix this code? It is really anoying that polish letters aren’t displayed. Where could be a problem?

<?php

 $DB_Server = "localhost";      //your MySQL Server 
$DB_Username = "******";                 //your MySQL User Name 
$DB_Password = "*****";             //your MySQL Password 
$DB_DBName = "*******";             //your MySQL Database Name 
$DB_TBLName = "********";               //your MySQL Table Name  

 $filename = "excelfilename";         //File Name

 //create MySQL connection
 $sql = "Select * from $DB_TBLName";
 $Connect = @mysql_connect($DB_Server, $DB_Username, $DB_Password)
 or die("Couldn't connect to MySQL:<br>" . mysql_error() . "<br>" . mysql_errno());
 //select database
 $Db = @mysql_select_db($DB_DBName, $Connect)
 or die("Couldn't select database:<br>" . mysql_error(). "<br>" . mysql_errno());
 //execute query
 $result = @mysql_query($sql,$Connect)
 or die("Couldn't execute query:<br>" . mysql_error(). "<br>" . mysql_errno());
 $file_ending = "xls";

//header info for browser
 header("Content-Type: application/xls");
 header("Content-Disposition: attachment; filename=$filename.xls");
 header("Pragma: no-cache");
 header("Expires: 0");

/*******Start of Formatting for Excel*******/
 //define separator (defines columns in excel & tabs in word)
 $sep = "t"; //tabbed character

//start of printing column names as names of MySQL fields
 for ($i = 0; $i < mysql_num_fields($result); $i++) {
 echo mysql_field_name($result,$i) . "t";
 }
 print("n");
 //end of printing column names

//start while loop to get data
 while($row = mysql_fetch_row($result))
 {
 $schema_insert = "";
 for($j=0; $j<mysql_num_fields($result);$j++)
 {
 if(!isset($row[$j]))
 $schema_insert .= "NULL".$sep;
 elseif ($row[$j] != "")
 $schema_insert .= "$row[$j]".$sep;
 else
 $schema_insert .= "".$sep;
 }
 $schema_insert = str_replace($sep."$", "", $schema_insert);
 $schema_insert = preg_replace("/rn|nr|n|r/", " ", $schema_insert);
 $schema_insert .= "t";
 print(trim($schema_insert));
 print "n";
 }
 ?>

asked Aug 6, 2014 at 13:50

Anna K's user avatar

6

You have to write what is charset of you database. If it is UTF8 try to execute query «SET NAMES utf8» after connection is established ;

And be shure that encoding of you page is UTF8. You can check encoding in Notepad++ utility

answered Aug 6, 2014 at 15:02

Vova Vasiuta's user avatar

Problem is your output is in ISO-8859-2 but excel expects Windows-1250 which has few characters shuffled around for Windows-1252 compatibility.

You can either convert your output to Windows-1250

echo mb_convert_encoding($str, 'Windows-1250', 'ISO-8859-2');

Or convert to utf8:

add utf8 BOM after headers and first thing as file content:

echo "xEFxBBxBF";

and convert data to utf8

echo mb_convert_encoding($str, 'UTF-8', 'ISO-8859-2');

If you have older excel that does not support utf8 you are out of luck.


By default excel assumes windows default locale which is different for people from different locations i.e person in US will likely see your text as «Brze¶æ, Bia³oru¶» instead

answered Aug 6, 2014 at 15:58

Imre L's user avatar

Imre LImre L

6,13923 silver badges32 bronze badges

1

  • #1

Проблема с кодировкой при импорте Excel в mySQL

Использую скрипт «Zakkis Php Excel Parser Pro v4.0» для формирования БД из excel-файла. Проблема состоит в том, что русские символы записываются в mySQL в виде кодов (вида &#XXX). Как я понимаю, проблема состоит в том, что данные в excel хранятся в unicode. У меня же в БД задана кодировка CP1251. При извлечении из БД в браузере русские символы отображаются коррекно, но они также заданы кодами. Очень хотелось бы узнать, как справиться с этой проблемой, т.е. как заносить данные в БД в нормальной кодировке.

Версия php: 4.3.10
Версия mysql: 4.1.8

Заранее спасибо за помощь! :)

  • #2

известная фича.

PHP:

$str=iconv('UNICODELITTLE','UTF-8',$str);

вместо UTF-8 поставить то, что нужно.

Понравилась статья? Поделить с друзьями:
  • Mysql for excel workbench
  • Mysql for excel for mac
  • Mysql for excel export data
  • Mysql export to excel file
  • Mysql connector для excel