TailTemplate Build stunning websites faster with our pre-designed Tailwind CSS templates

How to Read Excel File to Array in PHP

To read an Excel file and store the data in an array in PHP, you can use the PHPExcel library. Here is an example of how you can do this:

  • First, install the PHPExcel library using composer:
composer require phpoffice/phpexcel
  • Then, use the following code to read an Excel file and store the data in an array:

// include the PHPExcel library
require 'vendor/autoload.php';

// create a new instance of the PHPExcel object
$excel = new PHPExcel();

// read the Excel file
$excel->load('path/to/file.xlsx');

// get the active sheet
$sheet = $excel->getActiveSheet();

// get the highest row and column numbers
$highestRow = $sheet->getHighestRow();
$highestColumn = $sheet->getHighestColumn();

// loop through the rows and columns of the sheet
for ($row = 1; $row <= $highestRow; $row++) {
  for ($col = 'A'; $col <= $highestColumn; $col++) {
    // read the cell value and store it in the array
    $data[$row][$col] = $sheet->getCell($col . $row)->getValue();
  }
}

This code will read the data from the Excel file and store it in a two-dimensional array, where the first dimension represents the rows and the second dimension represents the columns. You can then access the individual cell values by using the row and column indices of the array, for example $data[3]['D'] will give you the value of the cell at row 3 and column D.