Tuesday, October 4, 2022

[FIXED] How to export data in multiple sheets in php

Issue

I have used PHPExcel class in php to export data but PHPExcel version 1.8 is deprecated in 2015.

Can I get any alternative solution for exporting multiple sheets.


Solution

You can use PHPSpreadhsheet. This is what the currently deprecated PHPExcel library has been continued as.


According to the docs. You will need to use the Composer package manager to install this library on your machine, by running the following command at the location of installation -

composer require phpoffice/phpspreadsheet

Include the library in your .php file in the following way -

<?php

    // load the classes provided by PHPSpreadSheet
    require 'vendor/autoload.php';

    use PhpOffice\PhpSpreadsheet\Spreadsheet;
    use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

    $spreadsheet = new Spreadsheet();

    // code to create and use worksheet goes here
?>

To create/add new worksheets you can use this function -

$spreadsheet->createSheet();

You can create multiple worksheets by using the above command in a for() or while() loop.

To get the worksheet and edit it, you can fetch it by index in the following way -

$spreadsheet->getSheet(1);

The above command will fetch the second sheet from the workbook (since the worksheets are always indexed from "0").



Answered By - sujaypatil
Answer Checked By - Mildred Charles (PHPFixing Admin)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.