Export csv to excel php

PHP: Exporting Data to 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:

«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] ]; ?>

Читайте также:  Array index length java

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:

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:

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.

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.

click here to trigger XLS download 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_20230722.xls» and will open in Excel looking something like this:

screenshot showing data in Excel colums

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:

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:

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:

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.

click here to trigger CSV download 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.

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:

‘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.

click here to trigger CSV download source

References

Источник

Преобразование CSV в XLSX на PHP

В статье приведены два примера конвертации фалов csv в xlsx, алгоритм следующий:

  • Файл открывается с помощью fopen() и построчно преобразуем функцией fgetcsv() в массив, в качестве разделителя обычно используется ,
  • Из полученного массива сформируется xlsx файл с помощью библиотеки PHPExcel.

Загрузка файлов через форму

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; > >

Преобразование на сервере

$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');

Источник

Оцените статью