Рубрики
Uncategorized

Простое использование электронной таблицы Php

Поскольку PHPExcel больше не поддерживается, Php Spreadsheet – это следующая версия PHPExcel. Php Spreadsheet – это библиотека, написанная на чистом PHP и представляющая пространства имен, спецификации PSR и т.д. Вот краткое введение в функции импорта и экспорта электронных таблиц Php. 1, установка Использует coUTF-8…

Поскольку PHPExcel больше не поддерживается, Php Spreadsheet – это следующая версия PHPExcel. Php Spreadsheet – это библиотека, написанная на чистом PHP и представляющая пространства имен, спецификации PSR и т.д. Вот краткое введение в функции импорта и экспорта электронных таблиц Php.

1, установка

  • Используйте composer для установки:
composer require phpoffice/phpspreadsheet
  • Скачать с GitHub:

https://github.com/PHPOffice/PhpSpreadsheet

2. экспорт файла excel

/**
 * excel File export
 */
function export()
{
    require_once __DIR__ . '/vendor/autoload.php';
 
    $data = [
        ['title1' => '111', 'title2' => '222'],
        ['title1' => '111', 'title2' => '222'],
        ['title1' => '111', 'title2' => '222']
    ];
    $title = ['Heading of the first line', 'Title of the second line'];
 
    // Create new Spreadsheet object
    $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
    $sheet = $spreadsheet->getActiveSheet();
 
    // Method 1: Use setCellValueByColumnAndRow
    //Header
    //Setting cell content
    foreach ($title as $key => $value) {
        // Cell content writing
        $sheet->setCellValueByColumnAndRow($key + 1, 1, $value);
    }
    $row = 2; // Start with the second line
    foreach ($data as $item) {
        $column = 1;
        foreach ($item as $value) {
            // Cell content writing
            $sheet->setCellValueByColumnAndRow($column, $row, $value);
            $column++;
        }
        $row++;
    }
 
    // Method 2: Use setCellValue
    //Header
    //Setting cell content
    $titCol = 'A';
    foreach ($title as $key => $value) {
        // Cell content writing
        $sheet->setCellValue($titCol . '1', $value);
        $titCol++;
    }
    $row = 2; // Start with the second line
    foreach ($data as $item) {
        $dataCol = 'A';
        foreach ($item as $value) {
            // Cell content writing
            $sheet->setCellValue($dataCol . $row, $value);
            $dataCol++;
        }
        $row++;
    }
 
    // Redirect output to a client's web browser (Xlsx)
    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    header('Content-Disposition: attachment;filename="01simple.xlsx"');
    header('Cache-Control: max-age=0');
    // If you're serving to IE 9, then the following may be needed
    header('Cache-Control: max-age=1');
 
    // If you're serving to IE over SSL, then the following may be needed
    header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
    header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
    header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
    header('Pragma: public'); // HTTP/1.0
 
    $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
    $writer->save('php://output');
    exit;
}

Результат:

3. Сохраняйте файлы excel локально

/**
 * excel Files are saved locally
 */
function save()
{
    require_once __DIR__ . '/vendor/autoload.php';
 
    $data = [
        ['title1' => '111', 'title2' => '222'],
        ['title1' => '111', 'title2' => '222'],
        ['title1' => '111', 'title2' => '222']
    ];
    $title = ['Heading of the first line', 'Title of the second line'];
 
    // Create new Spreadsheet object
    $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
    $sheet = $spreadsheet->getActiveSheet();
 
    //Header
    //Setting cell content
    $titCol = 'A';
    foreach ($title as $key => $value) {
        // Cell content writing
        $sheet->setCellValue($titCol . '1', $value);
        $titCol++;
    }
    $row = 2; // Start with the second line
    foreach ($data as $item) {
        $dataCol = 'A';
        foreach ($item as $value) {
            // Cell content writing
            $sheet->setCellValue($dataCol . $row, $value);
            $dataCol++;
        }
        $row++;
    }
 
    // Save
    $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
    $writer->save('01simple.xlsx');
}

4. Чтение содержимого файла excel

/**
 * Read excel file content
 */
function read()
{
    require_once __DIR__ . '/vendor/autoload.php';
    $inputFileName = dirname(__FILE__) . '/01simple.xlsx';
    $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($inputFileName);
    // Method two
    $sheetData = $spreadsheet->getActiveSheet()->toArray(null, true, true, true);
    return $sheetData;
}

Результат:

Потенциальные проблемы:

1, Фатальная ошибка: Неперехваченная ошибка: Класс ‘PHPOffice\PhpSpreadsheet\Spreadsheet’ не найден

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

require_once __DIR__ . '/vendor/autoload.php';

Или:

require_once __DIR__ . '/vendor/phpoffice/phpspreadsheet/src/Bootstrap.php';

2, Фатальная ошибка: Интерфейс ‘Psr\SimpleCache\CacheInterface’ не найден

Это происходит потому, что нет файла pst и нет модуля простого кэша. Если вы установите его с помощью composer, он будет сгенерирован автоматически. Если нет, вы можете загрузить его вручную.

Адрес для загрузки на GitHub: https://github.com/php-fig/simple-cache/releases

Оригинал: “https://programmer.help/blogs/simple-use-of-php-spreadsheet.html”