Open In App

PHP | Spreadsheet

Last Updated : 07 Mar, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Introduction: PHPSpreadsheet is a library written in PHP which helps to read from and write to different types of spreadsheet file formats with the help of a given set of classes. The various format which support spreadsheet are Excel(.xlsx), Open Document Format(.ods),SpreadsheetML(.xml), CSV and many more.

Advantages:

  • Easy and effective comparisons.
  • Powerful analysis of large amounts of data.

Usability:

  • Agendas
  • Budgets
  • Calendars
  • Cards
  • Charts and Diagrams
  • Financial Tools (Loan calculators etc.)
  • Flyers
  • Forms
  • Inventories
  • Invoices
  • Lists and to-do checklists
  • Planners
  • Plans and proposals
  • Reports
  • Schedules
  • Timesheets

Requirements: The following software is developed using PHPSpreadsheet:

  • PHP version 5.6 or newer
  • PHP extension php_zip enabled
  • PHP extension php_xml enabled
  • PHP extension php_gd2 enabled

Installation: The PHPSpreadsheet can be installed with the help of Composer.

On Terminal: The following command runs on the terminal to install PHPSpreadsheet: 

composer require phpoffice/phpspreadsheet


Example 1:

PHP
<?php

// require_once('vendor/autoload.php');
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

// Creates New Spreadsheet
$spreadsheet = new Spreadsheet();

// Retrieve the current active worksheet
$sheet = $spreadsheet->getActiveSheet();

// Set the value of cell A1
$sheet->setCellValue('A1', 'GeeksForGeeks!');

// Sets the value of cell B1
$sheet->setCellValue('B1', 'A Computer Science Portal For Geeks');
 
// Write an .xlsx file 
$writer = new Xlsx($spreadsheet);

// Save .xlsx file to the current directory
$writer->save('gfg.xlsx');
?>

Output:

example 1


Example 2:

PHP
<?php

// require_once('path/vendor/autoload.php');
// Load an .xlsx file
$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load('gfg.xlsx');
 
// Store data from the activeSheet to the variable
// in the form of Array
 
$data = array(1,$spreadsheet->getActiveSheet()
            ->toArray(null,true,true,true));

// Display the sheet content
var_dump($data);
?>

Output:

array(2) { 
    [0]=> int(1) 
    [1]=> array(1) { 
        [1]=> array(2) {
            ["A"]=> string(14) "GeeksForGeeks!" 
            ["B"]=> string(35) "A Computer Science Portal For Geeks"
        } 
    }
}

Next Article

Similar Reads