Export csv to excel php

Is there a way to convert csv file to excel file upon request through apache/.htaccess

hakre's user avatar

hakre

190k52 gold badges431 silver badges826 bronze badges

asked Oct 6, 2010 at 16:38

Ashraf Sufian's user avatar

3

Using PHPExcel

include 'PHPExcel/IOFactory.php';

$objReader = PHPExcel_IOFactory::createReader('CSV');

// If the files uses a delimiter other than a comma (e.g. a tab), then tell the reader
$objReader->setDelimiter("t");
// If the files uses an encoding other than UTF-8 or ASCII, then tell the reader
$objReader->setInputEncoding('UTF-16LE');

$objPHPExcel = $objReader->load('MyCSVFile.csv');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('MyExcelFile.xls');

vard's user avatar

vard

4,0572 gold badges26 silver badges46 bronze badges

answered Oct 6, 2010 at 22:21

Mark Baker's user avatar

Mark BakerMark Baker

208k31 gold badges340 silver badges383 bronze badges

2

PHPExcel is deprecated. You must use PhpSpreadsheet.

With PhpSpreadsheet, you can convert csv to xlsx by the following code:

$reader = PhpOfficePhpSpreadsheetIOFactory::createReader('Csv');

// If the files uses a delimiter other than a comma (e.g. a tab), then tell the reader
// $reader->setDelimiter("t");
// If the files uses an encoding other than UTF-8 or ASCII, then tell the reader
// $reader->setInputEncoding('UTF-16LE');

$objPHPExcel = $reader->load('/home/superman/projects/test/csv-app/file.csv');
$objWriter = PhpOfficePhpSpreadsheetIOFactory::createWriter($objPHPExcel, 'Xlsx');
$objWriter->save('excel_file.xlsx');

Ignatius's user avatar

Ignatius

2,6332 gold badges19 silver badges32 bronze badges

answered Jul 18, 2019 at 12:04

user3785966's user avatar

user3785966user3785966

2,44025 silver badges18 bronze badges

Note: PHPExcel is now listed as DEPRECATED.

Users are directed to PhpSpreadsheet.

answered Jul 20, 2018 at 13:18

bagsmode's user avatar

bagsmodebagsmode

6557 silver badges7 bronze badges

Using PhpSpreadheet:

require '../../vendor/autoload.php';

use PhpOfficePhpSpreadsheetSpreadsheet;
use PhpOfficePhpSpreadsheetWriterXlsx;

$spreadsheet = new Spreadsheet();
$reader = new PhpOfficePhpSpreadsheetReaderCsv();

/* Set CSV parsing options */

$reader->setDelimiter(',');
$reader->setEnclosure('"');
$reader->setSheetIndex(0);

/* Load a CSV file and save as a XLS */

$spreadsheet = $reader->load('../../uploads/test.csv');
$writer = new Xlsx($spreadsheet);
$writer->save('test.xlsx');

$spreadsheet->disconnectWorksheets();
unset($spreadsheet);

This one worked for me like a charm ! Cheers !!!

answered Mar 5, 2020 at 9:33

Plabon Dutta's user avatar

Plabon DuttaPlabon Dutta

6,6893 gold badges29 silver badges33 bronze badges

Yes, since apache is open-source, you can modify the .htaccess parser to call a library to convert your CSV files into excel files. But I don’t think this is what you’re looking for. :-).

I think really what you need is a dynamic web site. Then you can use PHP or any supported language to do what you need to do.

something like this:
http://www.westwideweb.com/wp/2009/01/12/convert-csv-to-xls-excel-in-php/

answered Oct 6, 2010 at 17:22

gtrak's user avatar

gtrakgtrak

5,5604 gold badges32 silver badges41 bronze badges

There is a project in sourceforge that does this conversion:

http://sourceforge.net/projects/py-csv2xls/

But for the conversion you need to make a dynamic page in apache (in python, php…)

answered Oct 7, 2010 at 14:02

Pablo Alba's user avatar

Pablo AlbaPablo Alba

1311 gold badge2 silver badges6 bronze badges

1

В статье приведены два примера конвертации фалов 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

export csv

Привет. Очень часто возникает необходимость экспортировать какие-то данные с сайта в Excel таблицу, например внутри личного кабинета компании формировать какой-то отчет и выгрузить его в формате CSV. PHP отлично с этим справляется и даже существуют специальные библиотеки, которые в значительной степени упрощают работу с экспортом данных в Excel. Но в данном примере мы их рассматривать не будем, а научимся это делать на чистом PHP. Ранее я публиковал материалы по созданию CRUD приложения на PHP, где мы помещали в базу данных некую информацию и выводили е на страницу. Я покажу, как можно сделать запись этих данных в CSV файл. И то же самое мы реализуем из другого приложения, где мы делали веб-приложение и хранили все записи в JSON файле. Как это выглядит можно посмотреть на демо странице:

Телеграм-канал serblog.ru

Демо

Экспорт в 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>

export-button-csv
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 файл с данными:
test-export-csv-php

Эта таблица полностью повторяет все, что находится в базе данных MySQL, только в обратном порядке.

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

export_excel_php
И запись в CSV из PHP
excel_php_export

Искренне надеюсь, что у меня получилось донести до вас информацию на тему экспорта из PHP CSV файл, а это значит, что мы можем открывать его в Excel. Если что — пишите комментарии.


This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters

Show hidden characters

UTF-16LE solution for CSV for Excel by Eugene Murai works well:
$unicode_str_for_Excel = chr(255).chr(254).mb_convert_encoding( $utf8_str, ‘UTF-16LE’, ‘UTF-8’);
However, then Excel on Mac OS X doesn’t identify columns properly and its puts each whole row in its own cell. In order to fix that, use TAB «\t» character as CSV delimiter rather than comma or colon.
You may also want to use HTTP encoding header, such as
header( «Content-type: application/vnd.ms-excel; charset=UTF-16LE» );
http://php.net/manual/en/ref.mbstring.php
PHP can input and output Unicode, but a little different from what Microsoft means: when Microsoft says «Unicode», it unexplicitly means little-endian UTF-16 with BOM(FF FE = chr(255).chr(254)), whereas PHP’s «UTF-16» means big-endian with BOM. For this reason, PHP does not seem to be able to output Unicode CSV file for Microsoft Excel. Solving this problem is quite simple: just put BOM infront of UTF-16LE string.
Example:
$unicode_str_for_Excel = chr(255).chr(254).mb_convert_encoding( $utf8_str, ‘UTF-16LE’, ‘UTF-8’);
http://stackoverflow.xluat.com/questions/18360770/trying-to-export-csv-in-microsoft-excel-with-special-character-like-chinese-but

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:

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:

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

Like this post? Please share to your friends:
  • Export csv for excel
  • Export collection to excel
  • Export array to excel
  • Explorer не открывает excel
  • Explorer word что это