How to open an Excel file with PHPExcel for both reading and writing?

PHPServer Side ProgrammingProgramming

There is no concept of opening a file for read and write in PHPExcel since it is not aware of the source of the PHPExcel object. Irrespective of the source from where the file was loaded or the type of file, the file can be read based on its named and saved with the same name. This way, the file will be overwritten, and new changes will be reflected in the file.


set_include_path(get_include_path() . PATH_SEPARATOR . './Classes/');
include 'PHPExcel/IOFactory.php';
$fileType = 'Excel5';
$fileName = name_of_file.xls';
// Read the file
$objReader = PHPExcel_IOFactory::createReader($fileType);
$objPHPExcel = $objReader->load($fileName);
// Change the file
   ->setCellValue('A1', 'Hello')
   ->setCellValue('B1', 'World!');
// Write the file
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, $fileType);


This will produce the following output −

Changes to cell A1, B1 are reflected in the name_of_file.xls file.

The time limit is set to 0 and the timezone is set to Europe/London. The filetype is known to be Excel and filename is assigned to the variable ‘fileName’. The ‘PHPExcel_IOFactory’ class ‘createReader’ is used to create the object and it is loaded using the ‘load’ function. Two cell values of the ‘xls’ sheet are changed and it is saved with the same named.

Published on 09-Apr-2020 14:57:19