PHP Reading And Writing Excel Files

Code Snippets Reading And Writing Excel Files


In this code snippet, we’ll learn how to read and write excel files in PHP.

We will use the PHPSpreadsheet library to read/write Excel files and we’ll learn how to read cells, find a specific string in a row or column, write to cells, set cell styling and formatting(like setting the border, background color, etc) and we’ll see how to insert images.

Let’s see how to do it in the example below.

Installing PHPSpreadsheet:

Install PHPSpreadsheet using Composer by opening your project directory in cmd and running this: 

composer require phpoffice/phpspreadsheet

If you don’t know what Composer is or how to use it check out this post I made.


You might have to enable the gd PHP extension for this to work. I first got this error:

Problem 1

    – Root composer.json requires phpoffice/phpspreadsheet ^1.18 -> satisfiable by phpoffice/phpspreadsheet[1.18.0].

    – phpoffice/phpspreadsheet 1.18.0 requires ext-gd * -> it is missing from your system. Install or enable PHP’s gd extension.

FIX: If you are using XAMPP like I am open up your php.ini file and add this: extension=gd to the bottom of it. Then save the file and restart the Apache webserver and try to install the package again. 

Reading Excel Files Code:


//Include the dependencies using Composer.
require_once(dirname(__FILE__) ."\\vendor\\autoload.php");
require_once(dirname(__FILE__) ."\\helperFunctions.php");

//Setup Excel reader///////////////////////////////////////////

//File to be read.
$inputFileName = dirname(__FILE__) . "\\readme.xlsx"; 
$sheetname = "First Sheet";

//Make a new instance of the Xlsx rader.
$reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
//Load the excel file to be read.
$spreadsheet = $reader->load($inputFileName);     
//Get the sheet by name.
$sheet = $spreadsheet->getSheetByName($sheetname);   


//Reading file/////////////////////////////////////////////////

//The row number of the header.
$columnNameRow = 1;
//The row number where our data starts.
$dataRow = $columnNameRow+1;

//If you don't know the exact column number you search for it with this helper function.
$column = findColumn($sheet, "greetings", $columnNameRow);
//Or if you need to search the rows:
//$row = findRow($sheet, "text to find", $column);

//Data array that will store the read data.
$readSheetData = [];

//Read rows until an empty one is hit.
$currentCellData = "/";
for($i = $dataRow; $currentCellData != ""; $i++){
    //Get cell data.
    $currentCellData = $sheet->getCellByColumnAndRow($column, $i)->getCalculatedValue();
    //If data is present add it to the data array. 
    if($currentCellData != null)
        $readSheetData[] = $currentCellData;

//Display data array.
foreach($readSheetData as $item)
    echo $item . "<br>";


//Helper functions//////////////////////////////////////////////

function findColumn($spreadsheet, $word, $row){
    $column = 1;
    $cellContent = $spreadsheet->getCellByColumnAndRow($column, $row)->getValue();
    while($cellContent != $word){
        $cellContent = $spreadsheet->getCellByColumnAndRow($column, $row)->getValue(); 

    return $column;

function findRow($spreadsheet, $word, $column){
    $row = 1;
    $cellContent = $spreadsheet->getCellByColumnAndRow($column, $row)->getValue();

    while($cellContent != $word) {
        $cellContent = $spreadsheet->getCellByColumnAndRow($column, $row)->getValue();                 

    return $row;


Resulting Output:

Writing Excel Files Code:


//Include the dependencies using Composer.
require_once(dirname(__FILE__) ."\\vendor\\autoload.php");

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

//Setup Excel writer////////////////////////////////////////////

//File to be read.
$inputFileName = dirname(__FILE__) . "readme.xlsx"; 
$sheetname = "First Sheet";

//Make a new spreadsheet.
$spreadsheet = new Spreadsheet();
//Get active sheet.
$sheet = $spreadsheet->getActiveSheet();
//Set sheet name.


//Writing file//////////////////////////////////////////////////

$dataToWrite1 = [ 15465, 532185, 2566, 54886 ];
$dataToWrite2 = [ 5694, 56964, 321789, 45623 ];

//Make header(optional).
$sheet->setCellValue('A1', "Data Set 1");
$sheet->setCellValue('B1', "Data Set 2");
//Make a bottom border(optional).
//Set header background color(optional).
//Set text bold.
//Set auto resize(optional).

//For more styling/formatting info. check out the official documentation:

//Write data 1.
$i = 2;
foreach($dataToWrite1 as $item){
    //Write value into cell.
    $sheet->setCellValue('A'.$i, $item);
    //Set cell alignment(optional).


//Write data 2.
$i = 2;
foreach($dataToWrite2 as $item){
    //Write value into cell.
    $sheet->setCellValue('B'.$i, $item);
    //Set cell alignment(optional).


//Adding an image.

//Create drawing.
$objDrawing = new \PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing();

//Get image path.
$imgPathName = dirname(__FILE__) . "\\PHP Reading And Writing Excel Files.jpg";    

//Create gdImage from image.
$gdImage = imagecreatefromjpeg($imgPathName);
//Set gdImage as a property to drawing.

//Set drawing properties.
$objDrawing->setDescription('PHP Reading And Writing Excel Files');
//Set file type.

//Set position.
//Set position offset.
//Set width and height.


//Write excel file.
$savePath = dirname(__FILE__);

$writer = new Xlsx($spreadsheet);
$writer->save($savePath . "\\New File.xlsx");


Resulting Output:


Leave a Reply

Your email address will not be published. Required fields are marked *

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger