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


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.

Example

error_reporting(E_ALL);
set_time_limit(0);
date_default_timezone_set('Europe/London');
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
$objPHPExcel->setActiveSheetIndex(0)
   ->setCellValue('A1', 'Hello')
   ->setCellValue('B1', 'World!');
// Write the file
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, $fileType);
$objWriter->save($fileName);

Output

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.

Updated on: 09-Apr-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements