phpphpoffice-phpspreadsheet

I cant get the PhpSpreadsheet library to generates an excel sheet


I use the following small PHP script using the PhpSpreadsheet library 1.29. Unfortunately I can't get the script to open an excel sheet. I don't get any error messages.

On my Windows PC I use XAMPP Version: 8.2.4
On the Server I use PHP 8.2
Composer version 2.6.6 2023-12-08 18:32:26

I installed the PhpSpreadsheet library with composer require phpoffice/phpspreadsheet

Using version ^1.29 for phpoffice/phpspreadsheet

I uploaded the files in the vendor/phpoffice directory to the server.

<?php

// Autoloader für Composer
require 'vendor/autoload.php';

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\IOFactory;

$spreadsheet = new Spreadsheet();

//Specify the properties for this document
$spreadsheet->getProperties()
    ->setTitle('PHP Download Example')
    ->setSubject('A PHPExcel example')
    ->setDescription('A simple example for PhpSpreadsheet. This class replaces the PHPExcel class')
    ->setCreator('php-download.com')
    ->setLastModifiedBy('php-download.com');

//Adding data to the excel sheet
$spreadsheet->setActiveSheetIndex(0)
    ->setCellValue('A1', 'This')
    ->setCellValue('A2', 'is')
    ->setCellValue('A3', 'only')
    ->setCellValue('A4', 'an')
    ->setCellValue('A5', 'example');


$writer = IOFactory::createWriter($spreadsheet, "Xlsx"); //Xls is also possible
$writer->save("zz_excel_file.xlsx");

?>

I'm expecting that $spreadsheet = new Spreadsheet(); will open the spreadsheet, but it doesn't


Solution

  • Your example should work as expected.

    But you're using relative paths, and that could be a problem.

    require 'vendor/autoload.php';
    
    $writer->save("zz_excel_file.xlsx");
    

    The file is probably being written, but not to the location you expect. It is worth either building paths using the __DIR__ constant, or absolute paths from configuration files.