В статье приведены два примера конвертации фалов 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
Is there a way to convert csv file to excel file upon request through apache/.htaccess
hakre
190k52 gold badges431 silver badges826 bronze badges
asked Oct 6, 2010 at 16:38
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
4,0572 gold badges26 silver badges46 bronze badges
answered Oct 6, 2010 at 22:21
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
2,6332 gold badges19 silver badges32 bronze badges
answered Jul 18, 2019 at 12:04
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
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 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
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 AlbaPablo Alba
1311 gold badge2 silver badges6 bronze badges
1
Содержание
- Как в PHP делать импорт/экспорт CSV для MS Excel
- Описание формата CSV для Excel
- Что делает стандартная функция экспорта в CSV в PHP
- Что делает стандартная функция импорта в CSV в PHP
- Итоговые функции работы с CSV
- Как открыть Экселем CSV-файл в кодировке UTF-8
- Reading and writing to file
- PhpOfficePhpSpreadsheetIOFactory
- Creating PhpOfficePhpSpreadsheetReaderIReader using PhpOfficePhpSpreadsheetIOFactory
- Creating PhpOfficePhpSpreadsheetWriterIWriter using PhpOfficePhpSpreadsheetIOFactory
- Excel 2007 (SpreadsheetML) file format
- PhpOfficePhpSpreadsheetReaderXlsx
- Reading a spreadsheet
- Read data only
- Read specific sheets only
- Read specific cells only
- PhpOfficePhpSpreadsheetWriterXlsx
- Writing a spreadsheet
- Formula pre-calculation
- Office 2003 compatibility pack
- Form Control Fields
- Excel 5 (BIFF) file format
- PhpOfficePhpSpreadsheetReaderXls
- Reading a spreadsheet
- Read data only
- Read specific sheets only
- Read specific cells only
- PhpOfficePhpSpreadsheetWriterXls
- Writing a spreadsheet
- Excel 2003 XML file format
- PhpOfficePhpSpreadsheetReaderXml
- Reading a spreadsheet
- Read specific cells only
- Symbolic LinK (SYLK)
- PhpOfficePhpSpreadsheetReaderSlk
- Reading a spreadsheet
- Read specific cells only
- Open/Libre Office (.ods)
- PhpOfficePhpSpreadsheetReaderOds
- Reading a spreadsheet
- Read specific cells only
- CSV (Comma Separated Values)
- PhpOfficePhpSpreadsheetReaderCsv
- Reading a CSV file
- Setting CSV options
- Read a specific worksheet
- Read into existing spreadsheet
- Line endings
- PhpOfficePhpSpreadsheetWriterCsv
- Writing a CSV file
- Setting CSV options
- CSV enclosures
- Write a specific worksheet
- Formula pre-calculation
- Writing UTF-8 CSV files
- Writing CSV files with desired encoding
- Decimal and thousands separators
- PhpOfficePhpSpreadsheetReaderHtml
- Reading a spreadsheet
- PhpOfficePhpSpreadsheetWriterHtml
- Writing a spreadsheet
- Write all worksheets
- Write a specific worksheet
- Setting the images root of the HTML file
- Formula pre-calculation
- Embedding generated HTML in a web page
- Editing HTML during save via a callback
- Decimal and thousands separators
- PhpOfficePhpSpreadsheetWriterPdf
- Custom implementation or configuration
- Writing a spreadsheet
- Write all worksheets
- Write a specific worksheet
- Setting Orientation and PaperSize
- Formula pre-calculation
- Editing Pdf during save via a callback
- Decimal and thousands separators
- Generating Excel files from templates (read, modify, write)
- Generating Excel files from HTML content
- Reader/Writer Flags
- Combining Flags
Как в PHP делать импорт/экспорт CSV для MS Excel
Многие, работая с PHP и MySQL, сталкивались с проблемой экспорта/импорта данных в CSV файл, понятный для Excel. Функции fputcsv() и fgetcsv() работают не так, как нам хотелось бы. И открывая полученный CSV-файл в Экселе мы видим половину строки в одной ячейке, а другую часть строки во второй. Иногда такие ошибки интерпретации данных Экселем связаны с его ограничением количества данных в одной ячейке – 50 000 символов, если больше, то оставшиеся данные отображаются в новой строке.
Описание формата CSV для Excel
Программа Microsoft Excel понимает CSV-файлы как разделенные ячейки, разделенные символом точка с запятой (;), а строка заканчивается символом перевода строки. Если же в самой ячейке содержатся символы точка с запятой (;) либо перехода на новую строку, то такая ячейка обрамляется символом кавычек («).
Например:
ячейка1; «ячейка2 с символом ; или в несколько строк»; ячейка3;
Если же в самой ячейке встречаются кавычки (”), то они удваиваются.
Например:
Это»кавычки; => Это»»кавычки;
Что делает стандартная функция экспорта в CSV в PHP
Функция fputcsv ($csv_file , $array, $delimiter = ‘,’, $enclosure = ‘»‘ ) выполняет экспорт массива $array в файл $csv_file. При этом в качестве разделителя по умолчанию используя запятую ($delimiter = ‘,’) ,а в качестве обрамляющего символа – кавычки ($enclosure = ‘»‘).
Казалось бы, чтобы записать данные в формат CSV для MS Excel нужно всего лишь установить $delimiter = ‘;’, а $enclosure оставить равным кавычкам (“), но в реальности случаются ошибки интерпретации файла Экселем.
Вот в чем подвох: функция fputcsv в качестве экранирующего символа – обратный слеш (). И это изменить никак нельзя. То есть, если вы будете писать данные вида лалал”лала, то при записи в файл этот символ кавычек не удвоится, потому что он экранирован обратным слешем, а значит, Эксель посчитает его границей ячейки, хотя это не так.
Выход: использовать свою функцию экспорта в CSV, далее будет приведен ее текст.
Что делает стандартная функция импорта в CSV в PHP
В PHP функция импорта из CSV-фала fgetcsv($csv_file, $length = 0, $delimiter = ‘,’, $enclosure = ‘»‘, $escape = ‘\’) импортирует из CSV-файла $csv_file строка максимальной длины $length, если = 0, значит, она может быть любой. По умолчанию в качестве разделителя использует символ запятой (,), в качестве обрамляющего символа – кавычки («), и символ экранирования – обратный слеш ().
Начиная с PHP версии 5.3 символ экранирования в этой функции можно задавать свой.
Чтобы экспортировать данные с помощью PHP в формат CSV для Экселя, достаточно ко всему прочему в качестве экранирующего символа установить кавычки. То есть $delimiter = ‘;’, $enclosure = ‘»‘, $escape = ‘»‘.
Итоговые функции работы с CSV
Как открыть Экселем CSV-файл в кодировке UTF-8
Чтобы Excel нормально открывал CSV-файлы в кодировке UTF-8 не достаточно просто записывать туда данные этой кодировке. Чтобы «подсказать» Экселю использовать юникод принято в начало файла вставлять 3х байтную последовательность: EF BB BF. Это не есть официальное решение, это просто особенность открытия Экселем CSV-файлов.
Для наглядности приведем кусок кода для PHP:
Далее уже экспортируем данные в кодировке UTF-8 при помощи функции my_fputcsv(). Excel отлично открывает такие файлы.
Важно! Несмотря на то, что файл откроется в кдировке utf-8, Excel его сохранит все равно в кодировке windows-1251.
Источник
Reading and writing to file
As you already know from the architecture, reading and writing to a persisted storage is not possible using the base PhpSpreadsheet classes. For this purpose, PhpSpreadsheet provides readers and writers, which are implementations of PhpOfficePhpSpreadsheetReaderIReader and PhpOfficePhpSpreadsheetWriterIWriter .
PhpOfficePhpSpreadsheetIOFactory
The PhpSpreadsheet API offers multiple methods to create a PhpOfficePhpSpreadsheetReaderIReader or PhpOfficePhpSpreadsheetWriterIWriter instance:
Direct creation via PhpOfficePhpSpreadsheetIOFactory . All examples underneath demonstrate the direct creation method. Note that you can also use the PhpOfficePhpSpreadsheetIOFactory class to do this.
Creating PhpOfficePhpSpreadsheetReaderIReader using PhpOfficePhpSpreadsheetIOFactory
There are 2 methods for reading in a file into PhpSpreadsheet: using automatic file type resolving or explicitly.
Automatic file type resolving checks the different PhpOfficePhpSpreadsheetReaderIReader distributed with PhpSpreadsheet. If one of them can load the specified file name, the file is loaded using that PhpOfficePhpSpreadsheetReaderIReader . Explicit mode requires you to specify which PhpOfficePhpSpreadsheetReaderIReader should be used.
You can create a PhpOfficePhpSpreadsheetReaderIReader instance using PhpOfficePhpSpreadsheetIOFactory in automatic file type resolving mode using the following code sample:
A typical use of this feature is when you need to read files uploaded by your users, and you don’t know whether they are uploading xls or xlsx files.
If you need to set some properties on the reader, (e.g. to only read data, see more about this later), then you may instead want to use this variant:
You can create a PhpOfficePhpSpreadsheetReaderIReader instance using PhpOfficePhpSpreadsheetIOFactory in explicit mode using the following code sample:
Note that automatic type resolving mode is slightly slower than explicit mode.
Creating PhpOfficePhpSpreadsheetWriterIWriter using PhpOfficePhpSpreadsheetIOFactory
You can create a PhpOfficePhpSpreadsheetWriterIWriter instance using PhpOfficePhpSpreadsheetIOFactory :
Excel 2007 (SpreadsheetML) file format
Xlsx file format is the main file format of PhpSpreadsheet. It allows outputting the in-memory spreadsheet to a .xlsx file.
PhpOfficePhpSpreadsheetReaderXlsx
Reading a spreadsheet
You can read an .xlsx file using the following code:
Read data only
You can set the option setReadDataOnly on the reader, to instruct the reader to ignore styling, data validation, … and just read cell data:
Read specific sheets only
You can set the option setLoadSheetsOnly on the reader, to instruct the reader to only load the sheets with a given name:
Read specific cells only
You can set the option setReadFilter on the reader, to instruct the reader to only load the cells which match a given rule. A read filter can be any class which implements PhpOfficePhpSpreadsheetReaderIReadFilter . By default, all cells are read using the PhpOfficePhpSpreadsheetReaderDefaultReadFilter .
The following code will only read row 1 and rows 20 – 30 of any sheet in the Excel file:
Read Filtering does not renumber cell rows and columns. If you filter to read only rows 100-200, cells that you read will still be numbered A100-A200, not A1-A101. Cells A1-A99 will not be loaded, but if you then try to call getCell() for a cell outside your loaded range, then PHPSpreadsheet will create a new cell with a null value.
Methods such as toArray() assume that all cells in a spreadsheet has been loaded from A1, so will return null values for rows and columns that fall outside your filter range: it is recommended that you keep track of the range that your filter has requested, and use rangeToArray() instead.
PhpOfficePhpSpreadsheetWriterXlsx
Writing a spreadsheet
You can write an .xlsx file using the following code:
Formula pre-calculation
By default, this writer pre-calculates all formulas in the spreadsheet. This can be slow on large spreadsheets, and maybe even unwanted. You can however disable formula pre-calculation:
Note Formulas will still be calculated in any column set to be autosized even if pre-calculated is set to false
Office 2003 compatibility pack
Because of a bug in the Office2003 compatibility pack, there can be some small issues when opening Xlsx spreadsheets (mostly related to formula calculation). You can enable Office2003 compatibility with the following code:
Office2003 compatibility option should only be used when needed because it disables several Office2007 file format options, resulting in a lower-featured Office2007 spreadsheet.
Form Control Fields
PhpSpreadsheet offers limited support for Forms Controls (buttons, checkboxes, etc.). The support is available only for Excel 2007 format, and is offered solely to allow loading a spreadsheet with such controls and saving it as a new file. Support is not available for adding such elements to the spreadsheet, nor even to locate them to determine their properties (so you can’t modify or delete them). Modifications to a worksheet with controls are «caveat emptor»; some modifications will work correctly, but others are very likely to cause problems, e.g. adding a comment to the worksheet, or inserting or deleting rows or columns in a manner that would cause the controls to change location.
Excel 5 (BIFF) file format
Xls file format is the old Excel file format, implemented in PhpSpreadsheet to provide a uniform manner to create both .xlsx and .xls files. It is basically a modified version of PEAR Spreadsheet_Excel_Writer, although it has been extended and has fewer limitations and more features than the old PEAR library. This can read all BIFF versions that use OLE2: BIFF5 (introduced with office 95) through BIFF8, but cannot read earlier versions.
Xls file format will not be developed any further, it just provides an additional file format for PhpSpreadsheet.
Excel5 (BIFF) limitations Please note that BIFF file format has some limits regarding to styling cells and handling large spreadsheets via PHP.
PhpOfficePhpSpreadsheetReaderXls
Reading a spreadsheet
You can read an .xls file using the following code:
Read data only
You can set the option setReadDataOnly on the reader, to instruct the reader to ignore styling, data validation, … and just read cell data:
Read specific sheets only
You can set the option setLoadSheetsOnly on the reader, to instruct the reader to only load the sheets with a given name:
Read specific cells only
You can set the option setReadFilter on the reader, to instruct the reader to only load the cells which match a given rule. A read filter can be any class which implements PhpOfficePhpSpreadsheetReaderIReadFilter . By default, all cells are read using the PhpOfficePhpSpreadsheetReaderDefaultReadFilter .
The following code will only read row 1 and rows 20 to 30 of any sheet in the Excel file:
PhpOfficePhpSpreadsheetWriterXls
Writing a spreadsheet
You can write an .xls file using the following code:
Excel 2003 XML file format
Excel 2003 XML file format is a file format which can be used in older versions of Microsoft Excel.
Excel 2003 XML limitations Please note that Excel 2003 XML format has some limits regarding to styling cells and handling large spreadsheets via PHP. Also, only files using charset UTF-8 are supported.
PhpOfficePhpSpreadsheetReaderXml
Reading a spreadsheet
You can read an Excel 2003 .xml file using the following code:
Read specific cells only
You can set the option setReadFilter on the reader, to instruct the reader to only load the cells which match a given rule. A read filter can be any class which implements PhpOfficePhpSpreadsheetReaderIReadFilter . By default, all cells are read using the PhpOfficePhpSpreadsheetReaderDefaultReadFilter .
The following code will only read row 1 and rows 20 to 30 of any sheet in the Excel file:
Symbolic LinK (SYLK)
Symbolic Link (SYLK) is a Microsoft file format typically used to exchange data between applications, specifically spreadsheets. SYLK files conventionally have a .slk suffix. Composed of only displayable ANSI characters, it can be easily created and processed by other applications, such as databases.
SYLK limitations Please note that SYLK file format has some limits regarding to styling cells and handling large spreadsheets via PHP.
PhpOfficePhpSpreadsheetReaderSlk
Reading a spreadsheet
You can read an .slk file using the following code:
Read specific cells only
You can set the option setReadFilter on the reader, to instruct the reader to only load the cells which match a given rule. A read filter can be any class which implements PhpOfficePhpSpreadsheetReaderIReadFilter . By default, all cells are read using the PhpOfficePhpSpreadsheetReaderDefaultReadFilter .
The following code will only read row 1 and rows 20 to 30 of any sheet in the SYLK file:
Open/Libre Office (.ods)
Open Office or Libre Office .ods files are the standard file format for Open Office or Libre Office Calc files.
PhpOfficePhpSpreadsheetReaderOds
Reading a spreadsheet
You can read an .ods file using the following code:
Read specific cells only
You can set the option setReadFilter on the reader, to instruct the reader to only load the cells which match a given rule. A read filter can be any class which implements PhpOfficePhpSpreadsheetReaderIReadFilter . By default, all cells are read using the PhpOfficePhpSpreadsheetReaderDefaultReadFilter .
The following code will only read row 1 and rows 20 to 30 of any sheet in the Calc file:
CSV (Comma Separated Values)
CSV (Comma Separated Values) are often used as an import/export file format with other systems. PhpSpreadsheet allows reading and writing to CSV files.
CSV limitations Please note that CSV file format has some limits regarding to styling cells, number formatting, .
PhpOfficePhpSpreadsheetReaderCsv
Reading a CSV file
You can read a .csv file using the following code:
You can also treat a string as if it were the contents of a CSV file as follows:
Setting CSV options
Often, CSV files are not really «comma separated», or use semicolon ( ; ) as a separator. You can set some options before reading a CSV file.
The separator will be auto-detected, so in most cases it should not be necessary to specify it. But in cases where auto-detection does not fit the use-case, then it can be set manually.
Note that PhpOfficePhpSpreadsheetReaderCsv by default assumes that the loaded CSV file is UTF-8 encoded. If you are reading CSV files that were created in Microsoft Office Excel the correct input encoding may rather be Windows-1252 (CP1252). Always make sure that the input encoding is set appropriately.
You may also let PhpSpreadsheet attempt to guess the input encoding. It will do so based on a test for BOM (UTF-8, UTF-16BE, UTF-16LE, UTF-32BE, or UTF-32LE), or by doing heuristic tests for those encodings, falling back to a specifiable encoding (default is CP1252) if all of those tests fail.
You can also set the reader to guess the encoding rather than calling guessEncoding directly. In this case, the user-settable fallback encoding is used if nothing else works.
The CSV reader will normally not load null strings into the spreadsheet. To load them:
Finally, you can set a callback to be invoked when the constructor is executed, either through new Csv() or IOFactory::load , and have that callback set the customizable attributes to whatever defaults are appropriate for your environment.
Read a specific worksheet
CSV files can only contain one worksheet. Therefore, you can specify which sheet to read from CSV:
Read into existing spreadsheet
When working with CSV files, it might occur that you want to import CSV data into an existing Spreadsheet object. The following code loads a CSV file into an existing $spreadsheet containing some sheets, and imports onto the 6th sheet:
Line endings
Line endings for Unix ( n ) and Windows ( rn ) are supported.
Mac line endings ( r ) are supported as long as PHP itself supports them, which it does through release 8.0. Support for Mac line endings is deprecated for 8.1, and is scheduled to remain deprecated for all later PHP8 releases; PhpSpreadsheet will continue to support them for 8.*. Support is scheduled to be dropped with release 9; PhpSpreadsheet will then no longer handle CSV files with Mac line endings correctly.
You can suppress testing for Mac line endings as follows:
PhpOfficePhpSpreadsheetWriterCsv
Writing a CSV file
You can write a .csv file using the following code:
Setting CSV options
Often, CSV files are not really «comma separated», or use semicolon ( ; ) as a separator. You can set some options before writing a CSV file:
CSV enclosures
By default, all CSV fields are wrapped in the enclosure character, which defaults to double-quote. You can change to use the enclosure character only when required:
Write a specific worksheet
CSV files can only contain one worksheet. Therefore, you can specify which sheet to write to CSV:
Formula pre-calculation
By default, this writer pre-calculates all formulas in the spreadsheet. This can be slow on large spreadsheets, and maybe even unwanted. You can however disable formula pre-calculation:
Writing UTF-8 CSV files
CSV files are written in UTF-8. If they do not contain characters outside the ASCII range, nothing else need be done. However, if such characters are in the file, or if the file starts with the 2 characters ‘ID’, it should explicitly include a BOM file header; if it doesn’t, Excel will not interpret those characters correctly. This can be enabled by using the following code:
Writing CSV files with desired encoding
It can be set to output with the encoding that can be specified by PHP’s mb_convert_encoding. This looks like the following code:
Decimal and thousands separators
If the worksheet you are exporting contains numbers with decimal or thousands separators then you should think about what characters you want to use for those before doing the export.
By default PhpSpreadsheet looks up in the server’s locale settings to decide what characters to use. But to avoid problems it is recommended to set the characters explicitly as shown below.
English users will want to use this before doing the export:
German users will want to use the opposite values.
Note that the above code sets decimal and thousand separators as global options. This also affects how HTML and PDF is exported.
PhpSpreadsheet allows you to read or write a spreadsheet as HTML format, for quick representation of the data in it to anyone who does not have a spreadsheet application on their PC, or loading files saved by other scripts that simply create HTML markup and give it a .xls file extension.
HTML limitations Please note that HTML file format has some limits regarding to styling cells, number formatting, . Also, only files using charset UTF-8 are supported.
PhpOfficePhpSpreadsheetReaderHtml
Reading a spreadsheet
You can read an .html or .htm file using the following code:
HTML limitations Please note that HTML reader is still experimental and does not yet support merged cells or nested tables cleanly
PhpOfficePhpSpreadsheetWriterHtml
Please note that PhpOfficePhpSpreadsheetWriterHtml only outputs the first worksheet by default.
Writing a spreadsheet
You can write a .htm file using the following code:
Write all worksheets
HTML files can contain one or more worksheets. If you want to write all sheets into a single HTML file, use the following code:
Write a specific worksheet
HTML files can contain one or more worksheets. Therefore, you can specify which sheet to write to HTML:
Setting the images root of the HTML file
There might be situations where you want to explicitly set the included images root. For example, instead of:
html
You might want to see:
You can use the following code to achieve this result:
Formula pre-calculation
By default, this writer pre-calculates all formulas in the spreadsheet. This can be slow on large spreadsheets, and maybe even unwanted. You can however disable formula pre-calculation:
Embedding generated HTML in a web page
There might be a situation where you want to embed the generated HTML in an existing website. PhpOfficePhpSpreadsheetWriterHtml provides support to generate only specific parts of the HTML code, which allows you to use these parts in your website.
- generateHTMLHeader()
- generateStyles()
- generateSheetData()
- generateHTMLFooter()
- generateHTMLAll()
Here’s an example which retrieves all parts independently and merges them into a resulting HTML page:
Editing HTML during save via a callback
You can also add a callback function to edit the generated html before saving. For example, you could change the gridlines from a thin solid black line:
Decimal and thousands separators
See section PhpOfficePhpSpreadsheetWriterCsv how to control the appearance of these.
PhpSpreadsheet allows you to write a spreadsheet into PDF format, for fast distribution of represented data.
PDF limitations Please note that PDF file format has some limits regarding to styling cells, number formatting, .
PhpOfficePhpSpreadsheetWriterPdf
PhpSpreadsheet’s PDF Writer is a wrapper for a 3rd-Party PDF Rendering library such as TCPDF, mPDF or Dompdf. You must now install a PDF rendering library yourself; but PhpSpreadsheet will work with a number of different libraries.
Currently, the following libraries are supported:
Library | Downloadable from | PhpSpreadsheet writer |
---|---|---|
TCPDF | https://github.com/tecnickcom/tcpdf | Tcpdf |
mPDF | https://github.com/mpdf/mpdf | Mpdf |
Dompdf | https://github.com/dompdf/dompdf | Dompdf |
The different libraries have different strengths and weaknesses. Some generate better formatted output than others, some are faster or use less memory than others, while some generate smaller .pdf files. It is the developers choice which one they wish to use, appropriate to their own circumstances.
You can instantiate a writer with its specific name, like so:
Or you can register which writer you are using with a more generic name, so you don’t need to remember which library you chose, only that you want to write PDF files:
Or you can instantiate directly the writer of your choice like so:
Custom implementation or configuration
If you need a custom implementation, or custom configuration, of a supported PDF library. You can extends the PDF library, and the PDF writer like so:
Writing a spreadsheet
Once you have identified the Renderer that you wish to use for PDF generation, you can write a .pdf file using the following code:
Please note that PhpOfficePhpSpreadsheetWriterPdf only outputs the first worksheet by default.
Write all worksheets
PDF files can contain one or more worksheets. If you want to write all sheets into a single PDF file, use the following code:
Write a specific worksheet
PDF files can contain one or more worksheets. Therefore, you can specify which sheet to write to PDF:
Setting Orientation and PaperSize
PhpSpreadsheet will attempt to honor the orientation and paper size specified in the worksheet for each page it prints, if the renderer supports that. However, you can set all pages to have the same orientation and paper size, e.g.
Formula pre-calculation
By default, this writer pre-calculates all formulas in the spreadsheet. This can be slow on large spreadsheets, and maybe even unwanted. You can however disable formula pre-calculation:
Editing Pdf during save via a callback
You can also add a callback function to edit the html used to generate the Pdf before saving. See under Html.
Decimal and thousands separators
See section PhpOfficePhpSpreadsheetWriterCsv how to control the appearance of these.
Generating Excel files from templates (read, modify, write)
Readers and writers are the tools that allow you to generate Excel files from templates. This requires less coding effort than generating the Excel file from scratch, especially if your template has many styles, page setup properties, headers etc.
Here is an example how to open a template file, fill in a couple of fields and save it again:
Notice that it is ok to load an xlsx file and generate an xls file.
Generating Excel files from HTML content
If you are generating an Excel file from pre-rendered HTML content you can do so automatically using the HTML Reader. This is most useful when you are generating Excel files from web application content that would be downloaded/sent to a user.
Suppose you have multiple worksheets you’d like created from html. This can be accomplished as follows.
Reader/Writer Flags
Some Readers and Writers support special «Feature Flags» that need to be explicitly enabled. An example of this is Charts in a spreadsheet. By default, when you load a spreadsheet that contains Charts, the charts will not be loaded. If all you want to do is read the data in the spreadsheet, then loading charts is an overhead for both speed of loading and memory usage. However, there are times when you may want to load any charts in the spreadsheet as well as the data. To do so, you need to tell the Reader explicitly to include Charts.
Alternatively, you can specify this in the call to load the spreadsheet:
If you wish to use the IOFactory load() method rather than instantiating a specific Reader, then you can still pass these flags.
Flags that are available that can be passed to the Reader in this way include:
- $reader::LOAD_WITH_CHARTS
- $reader::READ_DATA_ONLY
- $reader::IGNORE_EMPTY_CELLS
- $reader::SKIP_EMPTY_CELLS (synonym for IGNORE_EMPTY_CELLS)
Readers | LOAD_WITH_CHARTS | READ_DATA_ONLY | IGNORE_EMPTY_CELLS |
---|---|---|---|
Xlsx | YES | YES | YES |
Xls | NO | YES | YES |
Xml | NO | NO | NO |
Ods | NO | YES | NO |
Gnumeric | NO | YES | NO |
Html | N/A | N/A | N/A |
Slk | N/A | NO | NO |
Csv | N/A | NO | NO |
Likewise, when saving a file using a Writer, loaded charts will not be saved unless you explicitly tell the Writer to include them:
As with the load() method, you can also pass flags in the save() method:
Flags that are available that can be passed to the Reader in this way include:
- $reader::SAVE_WITH_CHARTS
- $reader::DISABLE_PRECALCULATE_FORMULAE
Writers | SAVE_WITH_CHARTS | DISABLE_PRECALCULATE_FORMULAE |
---|---|---|
Xlsx | YES | YES |
Xls | NO | NO |
Ods | NO | YES |
Html | YES | YES |
YES | YES | |
Csv | N/A | YES |
Combining Flags
One benefit of flags is that you can pass several flags in a single method call. Two or more flags can be passed together using PHP’s | operator.
Источник
Привет. Очень часто возникает необходимость экспортировать какие-то данные с сайта в 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. Если что — пишите комментарии.
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.