34

I'm using the PHPExcel library, and I'm creating xls objects either for writing or for reading:

PHPExcel_IOFactory::createReaderForFile('file.xlsx')
PHPExcel_IOFactory::createWriter('Excel2007')

How can I open an XLSX file for reading and writing?

Petruza
  • 11,744
  • 25
  • 84
  • 136

1 Answers1

58

You load a file into PHPExcel using a reader and the load() method, then save that file using a writer and the save() method... but PHPExcel itself is unaware of the source of the PHPExcel object... it doesn't care whether you have loaded it from a file (or what type of file) or created it by hand.

As such, there is no concept of "opening for read/write". You simply read the file by name, and save to the same filename. That will overwrite the original file with any changes that you have made in your script.

EDIT

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 = 'testFile.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);

And can I suggest that you read the documentation, and look at the sample code in /Tests

Mark Baker
  • 209,507
  • 32
  • 346
  • 385
  • 3
    Could you write sample code to explain this? I don't understand when you speak of `using a reader and the load() method, then save that file using a writer and the save() method` you are talking about two different objects, (a reader, a writer) but I need to open the file, modify some cells and save that same object to a file. – Petruza Jan 10 '12 at 19:46
  • this can cause a "Allowed memory size of xxxx bytes exhausted", can be fixed? – daver Aug 14 '13 at 14:09
  • It can probably be fixed be looking at the documented advice and recommendations for memory handling, such as using cell caching – Mark Baker Aug 14 '13 at 14:40
  • Thanks @MarkBaker. – Mubin Nov 26 '16 at 06:18
  • Works perfectly! – Thanh Nguyen Aug 07 '17 at 10:32