Php excel spreadsheet excel reader

В статье представлены различные PHP-расширения для чтения файлов XLS, XLSX, описаны их плюсы и минусы, а также примеры чтения.

1

PHPExcel

https://github.com/PHPOffice/PHPExcel

Огромная библиотека читает и формирует фалы xls, xlsx, csv.

  • Для файлов xlsx потребует расширение ZipArchive.
  • Потребляет много памяти.

Пример чтения файла в массив:

require_once __DIR__ . '/PHPExcel-1.8/Classes/PHPExcel/IOFactory.php';

// Файл xlsx
$xls = PHPExcel_IOFactory::load(__DIR__ . '/test.xlsx');

// Первый лист
$xls->setActiveSheetIndex(0);
$sheet = $xls->getActiveSheet();

foreach ($sheet->toArray() as $row) {
   print_r($row);
}

PHP

2

SimpleXLSX

https://www.phpclasses.org/package/6279-PHP-Parse-and-retrieve-data-from-Excel-XLS-files.html
simple-xlsx.zip (2017-09-25)

Читает только файлы xlsx.

  • Менее прожорлив к памяти.
  • Не всегда может прочитать файл, например файл сформированный PHPExcel.
require_once __DIR__ . '/simple-xlsx/simplexlsx.class.php'; 

// Файл xlsx
$xlsx = new SimpleXLSX(__DIR__ . '/test.xlsx');

// Первый лист
$sheet = $xlsx->rows(1);

foreach ($sheet as $row) {
   print_r($row);
}

PHP

3

PHP-ExcelReader

https://sourceforge.net/projects/phpexcelreader/
phpExcelReader.zip (исправленный)

  • Прочтёт только XLS файлы.
  • Есть проблемы с кодировкой.
require_once __DIR__ . '/phpExcelReader/Excel/reader.php';   

$data = new Spreadsheet_Excel_Reader();
$data->setOutputEncoding('UTF-8');

// Файл xls
$data->read(__DIR__ . '/test.xls');

// Первый лист
$sheet = $data->sheets[0]['cells'];

foreach ($sheet as $row) {
	print_r($row);
}

PHP

4

PHP-Excel-Reader

https://code.google.com/archive/p/php-excel-reader/
php-excel-reader.zip (2.21)

Форк библиотеки «PHP Excel Reader» с SourceForge предназначенный для вывода таблицы в HTML.

Например файл example.xls выведет следующим образом:

<style>
table.excel {
	border: 1px solid #CCCCCC;
	border-collapse:collapse;
	font-family:sans-serif;
	font-size:12px;
	margin: 0 auto;
}
table.excel thead th, table.excel tbody th {
	border: 1px solid #CCCCCC;
	text-align: center;
	vertical-align:bottom;
}
table.excel tbody th {
	text-align:center;
	width:20px;
}
table.excel tbody td {
	vertical-align:bottom;
}
table.excel tbody td {
	padding: 0 3px;
	border: 1px solid #EEEEEE;
}
</style>

<?php
require_once __DIR__ . '/php-excel-reader/excel_reader2.php';   
$data = new Spreadsheet_Excel_Reader(__DIR__ . '/example.xls');
echo $data->dump(true, true);
?>

HTML

Также у библиотеки есть методы для получения формата и содержания каждой ячейки по отдельности.

5

Nuovo Spreadsheet-Reader

https://github.com/nuovo/spreadsheet-reader
spreadsheet-reader.zip

Читает файлы XLSX, XLS, CSV и OpenOffice ods. Для чтения XLS используется предыдущая библиотека php-excel-reader.

require_once __DIR__ . '/spreadsheet-reader/php-excel-reader/excel_reader2.php';    
require_once __DIR__ . '/spreadsheet-reader/SpreadsheetReader.php';    

// Файл xlsx, xls, csv, ods.
$Reader = new SpreadsheetReader(__DIR__ . '/test.xlsx');

// Номер листа.
$Reader -> ChangeSheet(0);

foreach ($Reader as $Row) {
	print_r($Row);
}

PHP

6

PHP-Spreadsheetreader

https://code.google.com/archive/p/php-spreadsheetreader/
SpreadsheetReader.rar

Откроет только файлы в формате XML Excel 2004.

$file = __DIR__ . '/test.xml';

require_once __DIR__ . '/SpreadsheetReader/SpreadsheetReader.php';    
$reader = new SpreadsheetReader;

// Файл xml
$sheets = $reader->read(__DIR__ . '/test.xml');

// Выводим Первый лист
foreach ($sheets[0] as $row) {
   print_r($row);
}

PHP

PhpSpreadsheet

Build Status
Code Quality
Code Coverage
Total Downloads
Latest Stable Version
License
Join the chat at https://gitter.im/PHPOffice/PhpSpreadsheet

PhpSpreadsheet is a library written in pure PHP and offers a set of classes that
allow you to read and write various spreadsheet file formats such as Excel and LibreOffice Calc.

PHP Version Support

LTS: Support for PHP versions will only be maintained for a period of six months beyond the
end of life of that PHP version.

Currently the required PHP minimum version is PHP 7.4, and we will support that version until 28th June 2023.

See the composer.json for other requirements.

Installation

Use composer to install PhpSpreadsheet into your project:

composer require phpoffice/phpspreadsheet

If you are building your installation on a development machine that is on a different PHP version to the server where it will be deployed, or if your PHP CLI version is not the same as your run-time such as php-fpm or Apache’s mod_php, then you might want to add the following to your composer.json before installing:

{
    "require": {
        "phpoffice/phpspreadsheet": "^1.28"
    },
    "config": {
        "platform": {
            "php": "7.4"
        }
    }
}

and then run

to ensure that the correct dependencies are retrieved to match your deployment environment.

See CLI vs Application run-time for more details.

Additional Installation Options

If you want to write to PDF, or to include Charts when you write to HTML or PDF, then you will need to install additional libraries:

PDF

For PDF Generation, you can install any of the following, and then configure PhpSpreadsheet to indicate which library you are going to use:

  • mpdf/mpdf
  • dompdf/dompdf
  • tecnickcom/tcpdf

and configure PhpSpreadsheet using:

// Dompdf, Mpdf or Tcpdf (as appropriate)
$className = PhpOfficePhpSpreadsheetWriterPdfDompdf::class;
IOFactory::registerWriter('Pdf', $className);

or the appropriate PDF Writer wrapper for the library that you have chosen to install.

Chart Export

For Chart export, we support following packages, which you will also need to install yourself using composer require

  • jpgraph/jpgraph (this package was abandoned at version 4.0.
    You can manually download the latest version that supports PHP 8 and above from jpgraph.net)
  • mitoteam/jpgraph (fork with php 8.1 support)

and then configure PhpSpreadsheet using:

// to use jpgraph/jpgraph
Settings::setChartRenderer(PhpOfficePhpSpreadsheetChartRendererJpGraph::class);
//or
// to use mitoteam/jpgraph
Settings::setChartRenderer(PhpOfficePhpSpreadsheetChartRendererMtJpGraphRenderer::class);

One or the other of these libraries is necessary if you want to generate HTML or PDF files that include charts; or to render a Chart to an Image format from within your code.
They are not necessary to define charts for writing to Xlsx files.
Other file formats don’t support writing Charts.

Documentation

Read more about it, including install instructions, in the official documentation. Or check out the API documentation.

Please ask your support questions on StackOverflow, or have a quick chat on Gitter.

Patreon

I am now running a Patreon to support the work that I do on PhpSpreadsheet.

Supporters will receive access to articles about working with PhpSpreadsheet, and how to use some of its more advanced features.

Posts already available to Patreon supporters:

  • The Dating Game
    • A look at how MS Excel (and PhpSpreadsheet) handle date and time values.
  • Looping the Loop
    • Advice on Iterating through the rows and cells in a worksheet.

And for Patrons at levels actively using PhpSpreadsheet:

  • Behind the Mask
    • A look at Number Format Masks.

The Next Article (currently Work in Progress):

  • Formula for Success
    • How to debug formulae that don’t produce the expected result.

My aim is to post at least one article each month, taking a detailed look at some feature of MS Excel and how to use that feature in PhpSpreadsheet, or on how to perform different activities in PhpSpreadsheet.

Planned posts for the future include topics like:

  • Tables
  • Structured References
  • AutoFiltering
  • Array Formulae
  • Conditional Formatting
  • Data Validation
  • Value Binders
  • Images
  • Charts

After a period of six months exclusive to Patreon supporters, articles will be incorporated into the public documentation for the library.

PHPExcel vs PhpSpreadsheet ?

PhpSpreadsheet is the next version of PHPExcel. It breaks compatibility to dramatically improve the code base quality (namespaces, PSR compliance, use of latest PHP language features, etc.).

Because all efforts have shifted to PhpSpreadsheet, PHPExcel will no longer be maintained. All contributions for PHPExcel, patches and new features, should target PhpSpreadsheet master branch.

Do you need to migrate? There is an automated tool for that.

License

PhpSpreadsheet is licensed under MIT.

При построении различных сервисов, иногда бывает необходимость прочитать xlsx документ и с данными, которые в нем содержатся что-то сделать, записать в базу, вывести на страницу или переформатировать и снова записать в файл, вариантов много. В предыдущей статье, был описан процесс создания excel документов при помощи php, почитать можно здесь В этой статье будет использоваться тот же пакет phpoffice/phpspreadsheet, для работы с документами excel.

Структура проекта

├── Файл index.php
├── Файл composer.json
├── Обрабатываемый файл xlsx

Шаг 1 — установка пакета phpoffice/phpspreadsheet

Данная статья написана, с учетом того, что composer у Вас установлен, поэтому переходим к созданию файла composer.json, его содержание:

{
    "require": {
      "phpoffice/phpspreadsheet": "^1.18"
    }
}

В этой же директории запускаем команду composer require

После успешного выполнения этой команды, произойдет установка необходимых пакетов, с зависимостями, структура немного изменится, будет такой:

├── Файл index.php
├── Файл composer.json
├── Файл composer.lock
├── Обрабатываемый файл xlsx
├── Директория vendor
   └── Директории с файлами пакетов

Файл xlsx у меня с таким содержимым:

файл xlsx

В самом простом примере прочитаем файл xlsx в массив и выведем функцией print_r, для этого необходимо написать index.php, код будет такой:

<?php
set_include_path(__DIR__);

require './vendor/autoload.php';


use PhpOfficePhpSpreadsheetReaderXlsx;

$inputFileName = __DIR__ . '/file32342.xlsx';

$reader = new Xlsx();
$spreadsheet = $reader->load($inputFileName);

$sheetData = $spreadsheet->getActiveSheet()->toArray(null, true, true, true);


echo '<pre>';
print_r($sheetData);
echo '</pre>';

В результате выполнения этого кода, увидим вот такой распечатанный массив:

Array
(
    [1] => Array
        (
            [A] => Значение А1
            [B] => Значение В1
            [C] => Значение С1
            [D] => Значение D1
            [E] => Значение E1
            [F] => Значение F1
            [G] => Значение G1
            [H] => Значение H1
            [I] => Значение I1
            [J] => Значение J1
            [K] => Значение K1
            [L] => Значение L1
            [M] => Значение M1
        )

    [2] => Array
        (
            [A] => Значение А2
            [B] => Значение В2
            [C] => Значение С2
            [D] => Значение D2
            [E] => Значение E2
            [F] => Значение F2
            [G] => Значение G2
            [H] => Значение H2
            [I] => Значение I2
            [J] => Значение J2
            [K] => Значение K2
            [L] => Значение L2
            [M] => Значение M2
        )

    [3] => Array
        (
            [A] => Значение А3
            [B] => Значение В3
            [C] => Значение С3
            [D] => Значение D3
            [E] => Значение E3
            [F] => Значение F3
            [G] => Значение G3
            [H] => Значение H3
            [I] => Значение I3
            [J] => Значение J3
            [K] => Значение K3
            [L] => Значение L3
            [M] => Значение M3
        )

    [4] => Array
        (
            [A] => Значение А4
            [B] => Значение В4
            [C] => Значение С4
            [D] => Значение D4
            [E] => Значение E4
            [F] => Значение F4
            [G] => Значение G4
            [H] => Значение H4
            [I] => Значение I4
            [J] => Значение J4
            [K] => Значение K4
            [L] => Значение L4
            [M] => Значение M4
        )

    [5] => Array
        (
            [A] => Значение А5
            [B] => Значение В5
            [C] => Значение С5
            [D] => Значение D5
            [E] => Значение E5
            [F] => Значение F5
            [G] => Значение G5
            [H] => Значение H5
            [I] => Значение I5
            [J] => Значение J5
            [K] => Значение K5
            [L] => Значение L5
            [M] => Значение M5
        )

    [6] => Array
        (
            [A] => Значение А6
            [B] => Значение В6
            [C] => Значение С6
            [D] => Значение D6
            [E] => Значение E6
            [F] => Значение F6
            [G] => Значение G6
            [H] => Значение H6
            [I] => Значение I6
            [J] => Значение J6
            [K] => Значение K6
            [L] => Значение L6
            [M] => Значение M6
        )

    [7] => Array
        (
            [A] => Значение А7
            [B] => Значение В7
            [C] => Значение С7
            [D] => Значение D7
            [E] => Значение E7
            [F] => Значение F7
            [G] => Значение G7
            [H] => Значение H7
            [I] => Значение I7
            [J] => Значение J7
            [K] => Значение K7
            [L] => Значение L7
            [M] => Значение M7
        )

    [8] => Array
        (
            [A] => Значение А8
            [B] => Значение В8
            [C] => Значение С8
            [D] => Значение D8
            [E] => Значение E8
            [F] => Значение F8
            [G] => Значение G8
            [H] => Значение H8
            [I] => Значение I8
            [J] => Значение J8
            [K] => Значение K8
            [L] => Значение L8
            [M] => Значение M8
        )

    [9] => Array
        (
            [A] => Значение А9
            [B] => Значение В9
            [C] => Значение С9
            [D] => Значение D9
            [E] => Значение E9
            [F] => Значение F9
            [G] => Значение G9
            [H] => Значение H9
            [I] => Значение I9
            [J] => Значение J9
            [K] => Значение K9
            [L] => Значение L9
            [M] => Значение M9
        )

    [10] => Array
        (
            [A] => Значение А10
            [B] => Значение В10
            [C] => Значение С10
            [D] => Значение D10
            [E] => Значение E10
            [F] => Значение F10
            [G] => Значение G10
            [H] => Значение H10
            [I] => Значение I10
            [J] => Значение J10
            [K] => Значение K10
            [L] => Значение L10
            [M] => Значение M10
        )

    [11] => Array
        (
            [A] => Значение А11
            [B] => Значение В11
            [C] => Значение С11
            [D] => Значение D11
            [E] => Значение E11
            [F] => Значение F11
            [G] => Значение G11
            [H] => Значение H11
            [I] => Значение I11
            [J] => Значение J11
            [K] => Значение K11
            [L] => Значение L11
            [M] => Значение M11
        )

    [12] => Array
        (
            [A] => Значение А12
            [B] => Значение В12
            [C] => Значение С12
            [D] => Значение D12
            [E] => Значение E12
            [F] => Значение F12
            [G] => Значение G12
            [H] => Значение H12
            [I] => Значение I12
            [J] => Значение J12
            [K] => Значение K12
            [L] => Значение L12
            [M] => Значение M12
        )

    [13] => Array
        (
            [A] => Значение А13
            [B] => Значение В13
            [C] => Значение С13
            [D] => Значение D13
            [E] => Значение E13
            [F] => Значение F13
            [G] => Значение G13
            [H] => Значение H13
            [I] => Значение I13
            [J] => Значение J13
            [K] => Значение K13
            [L] => Значение L13
            [M] => Значение M13
        )

    [14] => Array
        (
            [A] => Значение А14
            [B] => Значение В14
            [C] => Значение С14
            [D] => Значение D14
            [E] => Значение E14
            [F] => Значение F14
            [G] => Значение G14
            [H] => Значение H14
            [I] => Значение I14
            [J] => Значение J14
            [K] => Значение K14
            [L] => Значение L14
            [M] => Значение M14
        )

    [15] => Array
        (
            [A] => Значение А15
            [B] => Значение В15
            [C] => Значение С15
            [D] => Значение D15
            [E] => Значение E15
            [F] => Значение F15
            [G] => Значение G15
            [H] => Значение H15
            [I] => Значение I15
            [J] => Значение J15
            [K] => Значение K15
            [L] => Значение L15
            [M] => Значение M15
        )

    [16] => Array
        (
            [A] => Значение А16
            [B] => Значение В16
            [C] => Значение С16
            [D] => Значение D16
            [E] => Значение E16
            [F] => Значение F16
            [G] => Значение G16
            [H] => Значение H16
            [I] => Значение I16
            [J] => Значение J16
            [K] => Значение K16
            [L] => Значение L16
            [M] => Значение M16
        )

    [17] => Array
        (
            [A] => Значение А17
            [B] => Значение В17
            [C] => Значение С17
            [D] => Значение D17
            [E] => Значение E17
            [F] => Значение F17
            [G] => Значение G17
            [H] => Значение H17
            [I] => Значение I17
            [J] => Значение J17
            [K] => Значение K17
            [L] => Значение L17
            [M] => Значение M17
        )

    [18] => Array
        (
            [A] => Значение А18
            [B] => Значение В18
            [C] => Значение С18
            [D] => Значение D18
            [E] => Значение E18
            [F] => Значение F18
            [G] => Значение G18
            [H] => Значение H18
            [I] => Значение I18
            [J] => Значение J18
            [K] => Значение K18
            [L] => Значение L18
            [M] => Значение M18
        )

    [19] => Array
        (
            [A] => Значение А19
            [B] => Значение В19
            [C] => Значение С19
            [D] => Значение D19
            [E] => Значение E19
            [F] => Значение F19
            [G] => Значение G19
            [H] => Значение H19
            [I] => Значение I19
            [J] => Значение J19
            [K] => Значение K19
            [L] => Значение L19
            [M] => Значение M19
        )

    [20] => Array
        (
            [A] => Значение А20
            [B] => Значение В20
            [C] => Значение С20
            [D] => Значение D20
            [E] => Значение E20
            [F] => Значение F20
            [G] => Значение G20
            [H] => Значение H20
            [I] => Значение I20
            [J] => Значение J20
            [K] => Значение K20
            [L] => Значение L20
            [M] => Значение M20
        )

    [21] => Array
        (
            [A] => Значение А21
            [B] => Значение В21
            [C] => Значение С21
            [D] => Значение D21
            [E] => Значение E21
            [F] => Значение F21
            [G] => Значение G21
            [H] => Значение H21
            [I] => Значение I21
            [J] => Значение J21
            [K] => Значение K21
            [L] => Значение L21
            [M] => Значение M21
        )

    [22] => Array
        (
            [A] => Значение А22
            [B] => Значение В22
            [C] => Значение С22
            [D] => Значение D22
            [E] => Значение E22
            [F] => Значение F22
            [G] => Значение G22
            [H] => Значение H22
            [I] => Значение I22
            [J] => Значение J22
            [K] => Значение K22
            [L] => Значение L22
            [M] => Значение M22
        )

    [23] => Array
        (
            [A] => Значение А23
            [B] => Значение В23
            [C] => Значение С23
            [D] => Значение D23
            [E] => Значение E23
            [F] => Значение F23
            [G] => Значение G23
            [H] => Значение H23
            [I] => Значение I23
            [J] => Значение J23
            [K] => Значение K23
            [L] => Значение L23
            [M] => Значение M23
        )

    [24] => Array
        (
            [A] => Значение А24
            [B] => Значение В24
            [C] => Значение С24
            [D] => Значение D24
            [E] => Значение E24
            [F] => Значение F24
            [G] => Значение G24
            [H] => Значение H24
            [I] => Значение I24
            [J] => Значение J24
            [K] => Значение K24
            [L] => Значение L24
            [M] => Значение M24
        )

    [25] => Array
        (
            [A] => Значение А25
            [B] => Значение В25
            [C] => Значение С25
            [D] => Значение D25
            [E] => Значение E25
            [F] => Значение F25
            [G] => Значение G25
            [H] => Значение H25
            [I] => Значение I25
            [J] => Значение J25
            [K] => Значение K25
            [L] => Значение L25
            [M] => Значение M25
        )

    [26] => Array
        (
            [A] => Значение А26
            [B] => Значение В26
            [C] => Значение С26
            [D] => Значение D26
            [E] => Значение E26
            [F] => Значение F26
            [G] => Значение G26
            [H] => Значение H26
            [I] => Значение I26
            [J] => Значение J26
            [K] => Значение K26
            [L] => Значение L26
            [M] => Значение M26
        )

    [27] => Array
        (
            [A] => Значение А27
            [B] => Значение В27
            [C] => Значение С27
            [D] => Значение D27
            [E] => Значение E27
            [F] => Значение F27
            [G] => Значение G27
            [H] => Значение H27
            [I] => Значение I27
            [J] => Значение J27
            [K] => Значение K27
            [L] => Значение L27
            [M] => Значение M27
        )

    [28] => Array
        (
            [A] => Значение А28
            [B] => Значение В28
            [C] => Значение С28
            [D] => Значение D28
            [E] => Значение E28
            [F] => Значение F28
            [G] => Значение G28
            [H] => Значение H28
            [I] => Значение I28
            [J] => Значение J28
            [K] => Значение K28
            [L] => Значение L28
            [M] => Значение M28
        )

    [29] => Array
        (
            [A] => Значение А29
            [B] => Значение В29
            [C] => Значение С29
            [D] => Значение D29
            [E] => Значение E29
            [F] => Значение F29
            [G] => Значение G29
            [H] => Значение H29
            [I] => Значение I29
            [J] => Значение J29
            [K] => Значение K29
            [L] => Значение L29
            [M] => Значение M29
        )

    [30] => Array
        (
            [A] => Значение А30
            [B] => Значение В30
            [C] => Значение С30
            [D] => Значение D30
            [E] => Значение E30
            [F] => Значение F30
            [G] => Значение G30
            [H] => Значение H30
            [I] => Значение I30
            [J] => Значение J30
            [K] => Значение K30
            [L] => Значение L30
            [M] => Значение M30
        )

)

В итоге все достаточно просто, каждая линия будет соответствовать номеру многомерного массива, где именами ключей будут выступать колонки их excel файла.

На смену PHPExcel пришла мощная библиотека PhpSpreadsheet от тех же разработчиков.

Документация: https://phpspreadsheet.readthedocs.io/en/latest/

API: https://phpoffice.github.io/PhpSpreadsheet/

Создание exсel файла

use PhpOfficePhpSpreadsheetSpreadsheet;
use PhpOfficePhpSpreadsheetWriterXlsx;

$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setTitle('Worksheet 1');
$sheet->setCellValue('A1', 'Hello World !');

// Writer можно создать так:
$writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
//$writer = new Xlsx($spreadsheet);
  
$writer->save($path . '/export/worksheet__' . date('Ymd_h:i:s') . '.xlsx');

$spreadsheet->disconnectWorksheets();

Запись данных в exсel с помощью итератора

Более информативный пример со стилями документа, строк, ячеек по условию.

use PhpOfficePhpSpreadsheetIOFactory;
use PhpOfficePhpSpreadsheetSpreadsheet;
use PhpOfficePhpSpreadsheetStyleColor;
use PhpOfficePhpSpreadsheetStyleConditionalFormattingWizard;
use PhpOfficePhpSpreadsheetStyleFill;
use PhpOfficePhpSpreadsheetStyleStyle;

try {
  $path = $path = realpath(__DIR__);

  // Способ #1. Стили для шапки
  $headerStyles = [
    'font'=>[
      'color'=>[
        'rgb' => '000'
      ],
      'bold' => true,
      'size' => 13
    ],
    'fill'=>[
        'fillType' => Fill::FILL_SOLID,
        'startColor' => [
          'rgb' => Color::COLOR_CYAN
        ]
    ],
  ];

  // Способ #2. Стили для данных
  $redStyle = new Style(false, true);
  $redStyle->getFill()
    ->setFillType(Fill::FILL_SOLID)
    ->getStartColor()->setARGB(Color::COLOR_RED);

  // Создание документа, листа и "писателя"
  $spreadsheet = new Spreadsheet();
  $sheet = $spreadsheet->getActiveSheet();
  // Название листа
  $sheet->setTitle('Worksheet 1');
  $writer = IOFactory::createWriter($spreadsheet, 'Xlsx'); 

  // Стили документа по умолчанию
  $spreadsheet->getDefaultStyle()
    ->getFont()
    ->setName('Arial')
    ->setSize(12);

  // Дополнительные стили
  // ...

  // Выравнивание по центру в строке
  //$spreadsheet->getActiveSheet()->getStyle('A1')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);

  // Установка стилей для шапки
  $spreadsheet->getActiveSheet()->getStyle('A1:F1')->applyFromArray($headerStyles);

  // Шапка
  $headerItems = [
    'First Name',
    'Last Name',
    'Email',
    'Gender',
    'Age',
    'Class'
  ];

  // Добавление шапки
  $sheet->fromArray($headerItems); // A1 start

  // Данные из файла для примера (чаще всего из базы данных)
  $file = file_get_contents('student-data.json');
  $studentData = json_decode($file,true);

  // Расчёт крайней правой точки листа
  $extremeCellValue = $sheet
    ->getCellByColumnAndRow(
        count($headerItems), count($studentData) + 1
    )
    ->getCoordinate();

  // Форматирование ячеки по условию (если студенту меньше 18 лет)
  $conditionalStyles = [];
  $wizardFactory = new Wizard("A1:$extremeCellValue");
  $textWizard = $wizardFactory->newRule(Wizard::CELL_VALUE);

  $textWizard->lessThan(18)
    ->setStyle($redStyle);
  $conditionalStyles[] = $textWizard->getConditional();

  $spreadsheet->getActiveSheet()
    ->getStyle($textWizard->getCellRange())
    ->setConditionalStyles($conditionalStyles);

  // Данные вставлять со 2-й строки
  $row = 2;
  foreach ($studentData as $student):
    unset($student['id']); // Исключаем id из данных (если необходимо)
    $sheet->fromArray($student, null, 'A'.$row); // A2 start
    $row++;
  endforeach;

  // Сохранение файла
  $writer->save($path . '/export/students_list__' . date('Ymd_h:i:s') . '.xlsx');
} catch (Exception $e) {
  $error = date('Y/m/d H:i:s') . ': ' . $e->getMessage() . PHP_EOL;
  error_log($error, 3, $path . '/runtime/app.log');
  die($e->getMessage() . PHP_EOL);
}

Чтение данных из файла exсel

use PhpOfficePhpSpreadsheetIOFactory;

$reader = IOFactory::createReader('Xlsx');
$spreadsheet = $reader->load('students_list.xlsx');
// Только чтение данных
$reader->setReadDataOnly(true);

// Количество листов
$sheetsCount = $spreadsheet->getSheetCount();
// Данные в виде массива
$data = $spreadsheet->getActiveSheet()->toArray();

foreach ($data as $item):
  var_dump($item);
endforeach;

php excelПо просьбам читателей сегодня пишу пост о дружбе MS Excel’я и PHP , сразу скажу

чтобы потом не закидали камнями

что дружат они ущербно , минут десять я потратил, чтобы найти разработку с помощью которой можно создавать excel’евские таблицы и ещё около часа искал класс с помощью которого это можно будет прочитать )) Начну с создания таблицы.

Есть класс под названием Excel Writer с помощью которого можно с лёгкостью создать excel’евский файлик вот таким образом
<?php

    include(«excelwriter.inc.php»);
    $excel=new ExcelWriter(«myXls.xls»);
    if($excel==false)   
        echo $excel->error;
    $myArr=array(«Name»,»Last Name»,»Address»,»Age»);
    $excel->writeLine($myArr);
    $myArr=array(«Sriram»,»Pandit»,»23 mayur vihar»,24);
    $excel->writeLine($myArr);

        $excel->writeRow();
    $excel->writeCol(«Manoj»);
    $excel->writeCol(«Tiwari»);
    $excel->writeCol(«80 Preet Vihar»);
    $excel->writeCol(24);

        $excel->writeRow();
    $excel->writeCol(«Harish»);
    $excel->writeCol(«Chauhan»);
    $excel->writeCol(«115 Shyam Park Main»);
    $excel->writeCol(22);

    $myArr=array(«Tapan»,»Chauhan»,»1st Floor Vasundhra»,25);
    $excel->writeLine($myArr);

        $excel->close();
    echo «data is write into myXls.xls Successfully.»;
?>


В папке со скриптом у меня появился файл myXls.xls , который открылся двумя экселями 2007 и 2003
php excel

Скачать класс:
http://www.phpclasses.org/browse/download/zip/package/2037/name/excelwriter-2004-12-30.zip
http://slil.ru/26310473

Для того чтобы читать таблицы созданные в excel’е вам понадобиться класс под названием Spreadsheet Excel Reader , для его работы необходим модуль PEAR, но на линукс хостинге у меня всё работало и так, без дополнительных установок. Еще в файле Excel/reader.php 31 строчку я заменил с
require_once ‘Spreadsheet/Excel/Reader/OLERead.php’;
на
require_once ‘Excel/oleread.inc’;
Пример у меня выглядел следующим образом:
<?php
require_once (‘Excel/reader.php’);

$data = new Spreadsheet_Excel_Reader();
$data->setOutputEncoding(‘cp-1251’);
$data->setUTFEncoder(‘mb’); $data->read(‘filename.xls’);

echo (‘<table>’);
 for ($i = 1; $i < = $data->sheets[0][‘numRows’]; $i++)
 {
  echo(‘<tr>’);
   for ($j = 1; $j < = $data->sheets[0][‘numCols’]; $j++)
   {
    echo (‘<td>’.$data->sheets[0][‘cells’][$i][$j].'</td>’);
   }
  echo(‘</tr>’);
 }
 echo (‘</table>’);
?>


Скрипт отлично распарсил созданный мною файл и выдал на экран такую же таблицу только в HTML’е.
Скачать класс:
http://downloads.sourceforge.net/phpexcelreader/phpExcelReader.zip

Я бы не советовал организовывать серьёзные проекты на классе Spreadsheet Excel Reader  , т.к. во время поиска увидел массу людей не довольных его работой, он плохо справляется с файлами состоящих из нескольких листов или с вычисляемыми полями. Встретил одну коммерческую разработку, которая творит чудеса и даже разбивает результат по листам ,вот демо проекта.

Блогун - монетизируем блоги

Понравилась статья? Поделить с друзьями:
  • Php excel read excel file
  • Php excel parser что это
  • Php excel from html
  • Php excel from array
  • Php excel and mysql