I notice that you need to consider:
Content-Type
header
BOM (Byte Order Mark)
Actual character encoding in the file
With BOM (works):
$bom = pack("CCC", 0xEF, 0xBB, 0xBF);
header('Content-Type: text/csv');
header('Content-Length: '.(strlen($csv)+strlen($bom)));
header('Content-Disposition: attachment;filename=my.csv');
echo $bom;
echo $csv;
Without BOM (works but you need to replace “smart quotes” then run utf8_decode
on each value or cell, and it converts some characters, for example FRĒ is converted to FRE’)
header('Content-Type: application/csv;charset=utf-8');
header('Content-Length: '.strlen($csv));
header('Content-Disposition: attachment;filename=my.csv');
echo $csv;
If the wrong combination of charset and BOM are used, it just comes out wrong when opening in MS Excel.
Bonus fact: mb_strlen
tells you the number of characters, strlen
tells you the number of bytes. You do NOT want to use mb_strlen
for calculating the Content-Length header.
Bonus 2: replace microsoft «smart» characters (em dash, curly quotes, etc):
$map = array(chr(145) => "'"
,chr(146) => "'"
,chr(147) => '"'
,chr(148) => '"'
,chr(149) => '-'
,chr(150) => '-'
,chr(151) => '-'
,chr(152) => '-'
,chr(152) => '-'
,chr(171) => '-'
,chr(187) => '-'
);
// faster that strtr
return str_replace( array_keys($map), $map, $str );
В статье приведены два примера конвертации фалов csv в xlsx, алгоритм следующий:
- Файл открывается с помощью
fopen()
и построчно преобразуем функциейfgetcsv()
в массив, в качестве разделителя обычно используется , - Из полученного массива сформируется xlsx файл с помощью библиотеки PHPExcel.
1
Загрузка файлов через форму
HTML форма
<form action="" method="post" enctype="multipart/form-data">
<div class="control-group">
<label class="control-label">Файл csv</label>
<div class="controls">
<input type="file" name="file">
</div>
</div>
<button type="submit">Отправить</button>
</form>
HTML
Обработчик формы
if (!empty($_FILES['file']['tmp_name'])) {
if (pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION) == 'csv') {
// Чтение файла в массив.
$list = array();
if (($fp = fopen($_FILES['file']['tmp_name'], 'r')) !== false) {
while (($data = fgetcsv($fp, 0, ',')) !== false) {
$list[] = $data;
}
fclose($fp);
}
// Подключение PHPExcel.
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();
// Формирование XLSX.
$line = 0;
foreach ($list as $line => $item) {
$line++;
foreach ($item as $col => $row) {
$sheet->setCellValueByColumnAndRow($col, $line, $row);
}
}
// Отдача файла в браузер.
$filename = basename($_FILES['file']['name'], '.csv') . '.xlsx';
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=' . $filename);
$objWriter = new PHPExcel_Writer_Excel2007($xls);
$objWriter->save('php://output');
exit;
}
}
PHP
2
Преобразование на сервере
$file = __DIR__ . '/list.csv';
// Чтение файла в массив.
$list = array();
if (($fp = fopen($file, 'r')) !== false) {
while (($data = fgetcsv($fp, 0, ',')) !== false) {
$list[] = $data;
}
fclose($fp);
}
// Подключение PHPExcel.
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();
// Формирование XLSX.
$line = 0;
foreach ($list as $line => $item) {
$line++;
foreach ($item as $col => $row) {
$sheet->setCellValueByColumnAndRow($col, $line, $row);
}
}
// Сохранение файла.
$objWriter = new PHPExcel_Writer_Excel2007($xls);
$objWriter->save(__DIR__ . '/' . basename($file, '.csv') . '.xlsx');
PHP
Привет. Очень часто возникает необходимость экспортировать какие-то данные с сайта в Excel таблицу, например внутри личного кабинета компании формировать какой-то отчет и выгрузить его в формате CSV. PHP отлично с этим справляется и даже существуют специальные библиотеки, которые в значительной степени упрощают работу с экспортом данных в Excel. Но в данном примере мы их рассматривать не будем, а научимся это делать на чистом PHP. Ранее я публиковал материалы по созданию CRUD приложения на PHP, где мы помещали в базу данных некую информацию и выводили е на страницу. Я покажу, как можно сделать запись этих данных в CSV файл. И то же самое мы реализуем из другого приложения, где мы делали веб-приложение и хранили все записи в JSON файле. Как это выглядит можно посмотреть на демо странице:
Демо
Экспорт в CSV из БД MySQL
Для начала подготовим кнопку, по нажатию которой на компьютер будет происходить загрузка CSV файла с экспортированными данными. Соответственно она должна быть обернута в тег form. Я использую Bootstrap и FontAwesome, поэтому добавлю еще иконку.
1 2 3 4 5 |
<form action="" method="post"> <button class="btn btn-primary mb-1" name="export_excel"> <i class="fa fa-file-csv"></i> Export</button> </form> |
PHP CSV
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
if (isset($_POST['export_exel'])) { header("Content-Type: text/csv; charset=utf-8"); header("Content-Disposition: attachment; filename=download.csv"); $output = fopen("php://output", "w"); fputcsv($output, array('ID', 'Имя', 'Фамилия', 'Ставка')); $sql = "SELECT * FROM `crud` ORDER BY `id` DESC"; $result = mysqli_query($mysqli, $sql); while ($row = mysqli_fetch_assoc($result)) { fputcsv($output, $row); } fclose($output); exit; } |
Нажимаем кнопку экспорта и получаем CSV файл с данными:
Эта таблица полностью повторяет все, что находится в базе данных MySQL, только в обратном порядке.
Если нужно экспортировать не все, а лишь некоторые ячейки таблицы, к примеру вы хотите из этой базы взять только Имя
Фамилию, то всего лишь нужно заменить пару строк кода:
5 |
fputcsv($output, array('Имя', 'Фамилия')); |
10 |
fputcsv($output, [$row['first'], $row['description']]); |
Конечно в этой БД полный бардак, но думаю, что принцип вам понятен. Для того, чтобы каждый раз вы экспортировали уникальный файл, то можно добавить в его имя временную метку:
И изменить 3 строчку на:
3 |
header("Content-Disposition: attachment; filename=download".$t .".csv"); |
Экспорт в CSV из JSON файла.
Как реализована запись в JSON — смотрите в предыдущем посте. Здесь будет чисто экспорт.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
if (isset($_POST['export_exсel'])) { $t = time(); header("Content-Type: text/csv; charset=utf-8"); header("Content-Disposition: attachment; filename=download".$t .".csv"); $output = fopen("php://output", "w"); fputcsv($output, ['ID', 'Задача']); foreach($jsonArray as $id => $arr) { fputcsv($output, [$id, $arr]); } fclose($output); exit; } |
И запись в CSV из PHP
Искренне надеюсь, что у меня получилось донести до вас информацию на тему экспорта из PHP CSV файл, а это значит, что мы можем открывать его в Excel. Если что — пишите комментарии.
After putting so much effort into importing your data into an SQL
database and connecting it to your website, how do you get it back out
and into Excel in order to keep your off-line and on-line systems
synchronised?
The following article presents a simple method for downloading any
data from PHP into an Excel spreadsheet — or at least something that
looks like one.
What we’re actually doing here is creating a
text (TAB or CSV) file containing the data which can then be opened by
Excel or any other spreadsheet. Before you ask, that means NO
formatting, NO colours and NO formulae — just the actual data.
For maximum compatibility with recent version of Excel, Numbers and
other applications you should use the CSV
download format rather than tab-delimted text.
Preparing the data
The following examples use the dataset created for and earlier
article Sorting Arrays of Arrays which is
defined as follows:
<?PHP
$data = [
["firstname" => "Mary", "lastname" => "Johnson", "age" => 25],
["firstname" => "Amanda", "lastname" => "Miller", "age" => 18],
["firstname" => "James", "lastname" => "Brown", "age" => 31],
["firstname" => "Patricia", "lastname" => "Williams", "age" => 7],
["firstname" => "Michael", "lastname" => "Davis", "age" => 43],
["firstname" => "Sarah", "lastname" => "Miller", "age" => 24],
["firstname" => "Patrick", "lastname" => "Miller", "age" => 27]
];
?>
Further down this page you will find examples for creating a
downloadable file using data sourced from an SQL query.
The first step is to output the data in a tab-delimited format (CSV
can also be used but is slightly more complicated). To achieve this we
use the following code:
<?PHP
header("Content-Type: text/plain");
$flag = FALSE;
foreach($data as $row) {
if(!$flag) {
// display field/column names as first row
echo implode("t", array_keys($row)) . "rn";
$flag = TRUE;
}
echo implode("t", array_values($row)) . "rn";
}
exit;
We set the content type to text/plain so that the output can
more easily be viewed in the browser. Otherwise, because there is no
HTML formatting, the output would appear as a single line of text.
The first line of output will be the column headings (in this case
the field names are used). Values are separated with a tab t
and rows with a line break n. The output should look
something like the following:
firstname lastname age
Mary Johnson 25
Amanda Miller 18
James Brown 31
Patricia Williams 7
Michael Davis 43
Sarah Miller 24
Patrick Miller 27
There’s already a weakness in this code that may not be immediately
obvious. What if one of the fields to be ouput already contains one or
more tab characters, or worse, a newline? That’s going to throw the
whole process out as we rely on those characters to indicate column- and
line-breaks.
The solution is to ‘escape’ the tab characters. In this case we’re
going to replace tabs with a literal t and line breaks with a
literal n so they don’t affect the formatting:
<?PHP
function cleanData(&$str)
{
$str = preg_replace("/t/", "\t", $str);
$str = preg_replace("/r?n/", "\n", $str);
}
header("Content-Type: text/plain");
$flag = FALSE;
foreach($data as $row) {
array_walk($row, __NAMESPACE__ . 'cleanData');
if(!$flag) {
// display field/column names as first row
echo implode("t", array_keys($row)) . "rn";
$flag = TRUE;
}
echo implode("t", array_values($row)) . "rn";
}
exit;
The __NAMESPACE__ reference and are required
to be compatible with PHP
Namespaces, and should be included whether or not you are currently
using namespaces for your code to be future-compatible.
Before each row is echoed any tab characters are replaced
«t» so that our columns aren’t broken up. Also any line
breaks within the data are replaced with «n». Now, how to
set this up as a download…
Triggering a download
What many programmers don’t realise is that you don’t have to create
a file, even a temporary one, in order for one to be downloaded. It’s
sufficient to ‘mimic’ a download by passing the equivalent HTTP headers
followed by the data.
If we create a PHP file with the following code then when it’s called
a file will be downloaded which can be opened directly using Excel.
<?PHP
function cleanData(&$str)
{
$str = preg_replace("/t/", "\t", $str);
$str = preg_replace("/r?n/", "\n", $str);
if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
}
// filename for download
$filename = "website_data_" . date('Ymd') . ".xls";
header("Content-Disposition: attachment; filename="$filename"");
header("Content-Type: application/vnd.ms-excel");
$flag = FALSE;
foreach($data as $row) {
array_walk($row, __NAMESPACE__ . 'cleanData');
if(!$flag) {
// display field/column names as first row
echo implode("t", array_keys($row)) . "rn";
$flag = TRUE;
}
echo implode("t", array_values($row)) . "rn";
}
exit;
Note that we’ve added an extra line to the cleanData
function to detect double-quotes and escape any value that contains
them. Without this an uneven number of quotes in a string can confuse
Excel.
source
This should result in a file being downloaded and saved to your
computer. If all goes well then the filename will be
named «website_data_20230414.xls» and will open in Excel looking something like this:
How does it work? Setting the headers tells the browser to expect a
file with a given name and type. The data is then echoed, but instead
of appearing on the page it becomes the downloaded file.
Because of the .xls extension and the vnd.ms-excel file
type, most computers will associate it with Excel and double-clicking
will cause that program to open. You could also modify the file name
and mime type to indicate a different spreadsheet package or database
application.
There is no way to specify data/cell formatting, column widths,
etc, using this method. To include formatting try generating HTML code
or a script that actually builds an Excel file. Or create your own
macro in Excel that applies formatting after the import.
A similar technique can be used to allow users to download files that
have been uploaded previously using PHP and stored with different names.
More on that later…
Exporting from an SQL database
If your goal is to allow data to be exported from a query result
then the changes are relatively simple:
<?PHP
// Original PHP code by Chirp Internet: www.chirpinternet.eu
// Please acknowledge use of this code by including this header.
function cleanData(&$str)
{
$str = preg_replace("/t/", "\t", $str);
$str = preg_replace("/r?n/", "\n", $str);
if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
}
// filename for download
$filename = "website_data_" . date('Ymd') . ".xls";
header("Content-Disposition: attachment; filename="$filename"");
header("Content-Type: application/vnd.ms-excel");
$flag = FALSE;
$result = pg_query("SELECT * FROM table ORDER BY field") or die('Query failed!');
while(FALSE !== ($row = pg_fetch_assoc($result))) {
array_walk($row, __NAMESPACE__ . 'cleanData');
if(!$flag) {
// display field/column names as first row
echo implode("t", array_keys($row)) . "rn";
$flag = TRUE;
}
echo implode("t", array_values($row)) . "rn";
}
exit;
This is the entire script required to query the database, clean the
data, and trigger a file download.
The database functions need to match the database you’re using.
MySQL users for example will need to use mysqli_query
and either mysqli_fetch_assoc or mysqli_fetch_assoc in place of the PostgreSQL
functions. Or better, PDO::query().
For other databases see under User Comments
below or check the PHP documentation.
If you are seeing duplicate
columns (numbered as well as labeled) you need to change the fetch call
to return only the associative (ASSOC) array.
If you’re having trouble at this stage, remove the
Content-Disposition header and change the Content-Type back to
text/plain. This makes debugging a lot easier as you can see
the output in your browser rather than having to download and open the
generated file every time you edit the script.
Preventing Excel’s ridiculous auto-format
When importing from a text file as we’re essentially doing here,
Excel has a nasty habit of mangling dates, timestamps, phone numbers and
similar input values.
For our purposes, some simple additions to the cleanData
function take care of most of the problems:
<?PHP
// Original PHP code by Chirp Internet: www.chirpinternet.eu
// Please acknowledge use of this code by including this header.
function cleanData(&$str)
{
// escape tab characters
$str = preg_replace("/t/", "\t", $str);
// escape new lines
$str = preg_replace("/r?n/", "\n", $str);
// convert 't' and 'f' to boolean values
if($str == 't') $str = 'TRUE';
if($str == 'f') $str = 'FALSE';
// force certain number/date formats to be imported as strings
if(preg_match("/^0/", $str) || preg_match("/^+?d{8,}$/", $str) || preg_match("/^d{4}.d{1,2}.d{1,2}/", $str)) {
$str = "'$str";
}
// escape fields that include double quotes
if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
}
?>
The section that prevents values being scrambled does so by inserting
an apostrophe at the start of the cell. When you open the resuling file
in Excel you may see the apostrophe, but editing the field will make it
disappear while retaining the string format. Excel is strange that way.
The types of values being escape this way are: values starting with a
zero; values starting with an optional + and at least 8
consecutive digits (phone numbers); and values starting with numbers in
YYYY-MM-DD format (timestamps). The relevant regular expressions have
been highlighted in the code above.
Exporting to CSV format
As newer versions of Excel are becoming fussy about opening files
with a .xls extension that are not actual Excel binary files, making CSV
format with a .csv extension is now a better option.
The tab-delimited text options describe above may be a bit limiting
if your data contains newlines or tab breaks that you want to preserve
when opened in Excel or another spreadsheet application.
A better format then is comma-separated variables (CSV) which can be
generated as follows:
<?PHP
// Original PHP code by Chirp Internet: www.chirpinternet.eu
// Please acknowledge use of this code by including this header.
function cleanData(&$str)
{
if($str == 't') $str = 'TRUE';
if($str == 'f') $str = 'FALSE';
if(preg_match("/^0/", $str) || preg_match("/^+?d{8,}$/", $str) || preg_match("/^d{4}.d{1,2}.d{1,2}/", $str)) {
$str = "'$str";
}
if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
}
// filename for download
$filename = "website_data_" . date('Ymd') . ".csv";
header("Content-Disposition: attachment; filename="$filename"");
header("Content-Type: text/csv");
$out = fopen("php://output", 'w');
$flag = FALSE;
$result = pg_query("SELECT * FROM table ORDER BY field") or die('Query failed!');
while(FALSE !== ($row = pg_fetch_assoc($result))) {
array_walk($row, __NAMESPACE__ . 'cleanData');
if(!$flag) {
// display field/column names as first row
fputcsv($out, array_keys($row), ',', '"');
$flag = TRUE;
}
fputcsv($out, array_values($row), ',', '"');
}
fclose($out);
exit;
Normally the fputcsv command is used to write data in CSV
format to a separate file. In this script we’re tricking it into
writing directly to the page by telling it to write to
php://output instead of a regular file. A nice trick.
source
As an aside, to export directly to CSV format from the command line
interface in PostgreSQL you can use simply:
postgres=# COPY (SELECT * FROM table ORDER BY field) TO '/tmp/table.csv' WITH CSV HEADER;
and for MySQL, something like the following:
SELECT * FROM table ORDER BY field
INTO OUTFILE '/tmp/table.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY 'n'
Exporting to CSV with Unicode intact
If like us your data contains UTF-8 characters you will notice that
Excel doesn’t handle them very well. Other applications can open UTF-8
content without problems, but Microsoft apparently still occupies the
dark ages.
Fortunately, there is a trick you can use. Below you can see how we
modify the script to convert everything from UTF-8 to UTF-16 Lower
Endian (UTF-16LE) format which Excel, at least on Windows, will recognise.
When opening this file in Excel you might find all the data
bunched into the first column. This should be fixable using the
«Text to Columns…» command under the Data menu.
<?PHP
// Original PHP code by Chirp Internet: www.chirpinternet.eu
// Please acknowledge use of this code by including this header.
function cleanData(&$str)
{
if($str == 't') $str = 'TRUE';
if($str == 'f') $str = 'FALSE';
if(preg_match("/^0/", $str) || preg_match("/^+?d{8,}$/", $str) || preg_match("/^d{4}.d{1,2}.d{1,2}/", $str)) {
$str = "'$str";
}
if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
$str = mb_convert_encoding($str, 'UTF-16LE', 'UTF-8');
}
// filename for download
$filename = "website_data_" . date('Ymd') . ".csv";
header("Content-Disposition: attachment; filename="$filename"");
header("Content-Type: text/csv; charset=UTF-16LE");
$out = fopen("php://output", 'w');
$flag = FALSE;
$result = pg_query("SELECT * FROM table ORDER BY field") or die('Query failed!');
while(FALSE !== ($row = pg_fetch_assoc($result))) {
array_walk($row, __NAMESPACE__ . 'cleanData');
if(!$flag) {
// display field/column names as first row
fputcsv($out, array_keys($row), ',', '"');
$flag = TRUE;
}
fputcsv($out, array_values($row), ',', '"');
}
fclose($out);
exit;
This script may not work for all versions of Excel. Please let us
know using the Feedback form below if you encounter problems or come up
with a better solution.
Changing column headings
The above database download examples all use the database field
names for the first row of the exported file which may not be what you
want. If you want to specify your own more user-friendly headings you
can modify the code as follow:
<PHP
$colnames = [
'memberno' => "Member No.",
'date_joined' => "Date joined",
'title' => "Title",
'firstname' => "First name",
'lastname' => "Last name",
'address' => "Address",
'postcode' => "Postcode",
'city' => "City",
'country' => "Country",
'phone' => "Telephone",
'mobile' => "Mobile",
'fax' => "Facsimile",
'email' => "Email address",
'notes' => "Notes"
];
function map_colnames($input)
{
global $colnames;
return isset($colnames[$input]) ? $colnames[$input] : $input;
}
// filename for download
$filename = "website_data_" . date('Ymd') . ".csv";
...
if(!$flag) {
// display field/column names as first row
$firstline = array_map(__NAMESPACE__ . 'map_colnames', array_keys($row));
fputcsv($out, $firstline, ',', '"');
$flag = TRUE;
}
...
?>
The values in the first row will be mapped according to the
$colnames associative array. If no mapping is provided for a
fieldname it will remain unchanged. Of course you will want to provide
your own list of suitable headings. They don’t have to be in order.
source
References
- Easy way to create XLS file from PHP
- Keeping leading zeros and large numbers
< PHP
Most recent 20 of 63 comments:
Post your comment or question
Database applications written in php often need to export data for reporting purpose. A popular export format is excel. Excel is a spreadsheet that lays out data in a grid format. Excel itself is a microsoft proprietory format. There are many libraries available for php like Spreadsheet_Excel_Writer pear package etc that can do the job. However these libraries need to be included with the application and are sometimes difficult to install.
If only a simple export in grid format is needed, then there are better solutions than excel. For example csv and tsv. These are very simple formats that can be generated with just a little code and are compatible with most spreadsheet applications like openoffice or ms-excel. Lets take a look at each of these.
1. CSV — Comma separated value
Another very simple format is csv : comma separated values format which can be opened in applications like ms-excel and openoffice.org spreadsheet. Can be written like this :
$data = '"Name","City","Country"' . "n"; $data .= '"Ashok","New Delhi","India"' . "n"; $data .= '"Krishna","Bangalore","India"' . "n"; $f = fopen('data.csv' , 'wb'); fwrite($f , $data ); fclose($f);
Both the above mentioned methods are powerful ways of representing tabular data being output from a database. Both the formats are very portable. There are some more rules to how to write csv files in proper format and can be read at the wikipedia article on the subject
2. TSV — Tab Separated Value Format
$data = '"Name"t"City"t"Country"' . "n"; $data .= '"Ashok"t"New Delhi"t"India"' . "n"; $data .= '"Krishna"t"Bangalore"t"India"' . "n"; $f = fopen('data.xls' , 'wb'); fwrite($f , $data ); fclose($f);
In that above example we are writing tabular data or say data from a database table into a file line by line and field by field. Its very simple to understand and read and at the same time its very portable as an export. That was nothing more than a simple tab delimited file (tsv : tab separated values) which Ms-excel , openoffice are comfortable at reading. And yes open it in excel and save as any other format you want. The filename can be ‘data.tsv’ if you like.
Conclusion
The above mentioned formats have many benefits over closed formats like excel. These formats are standard, portable and widely supported. They can be used for import directly in databases like mysql.
Unless there is a need to create complex formatting and media embedding, csv/tsv format should work well. If you need to create xlsx files however, check out the php library called phpexcel from codeplex.