简体   繁体   中英

PhpExcel write/save onto existing excel file

First of all, I have searched for my problem in both stackoverflow and on the forms, but I could not find exact question and its solution. ( This one is about saving HTML to existing Excel )

*** I have also seen some answers on related question about saving as new excel file, but my question is can I save onto existing excel file and if it is possible why I am getting an error when I open it.

QUESTION:

I have an existing excel-2010 template file with stock codes and dates.

在此处输入图像描述

I load/read this file with PHPexcel (read/load works fine) and I fill up with price values on some empty cells, then I am trying to save the file back with below code.

require_once __DIR__ . '/src/Classes/PHPExcel.php';
require_once __DIR__ . '/src/Classes/PHPExcel/IOFactory.php';

// read existing excel file
$readphpexcel = PHPExcel_IOFactory::load("polimer_uzex.xlsx");

// read the worksheet named "fetched"
$fetched = $readphpexcel->getSheetByName("fetched");

// make an array from all data on the worksheet
$exceldatas = $fetched->toArray(null, true, true, true);


/// ... some cell value modifications take place here on $exceldatas


// write to excell
$fetched->fromArray($exceldatas, null, 'A1', true);
$objWriter = PHPExcel_IOFactory::createWriter($readphpexcel, 'Excel5');// Excel 2010
$objWriter->save("polimer_uzex.xlsx");

After saving, I am getting below error (“Excel cannot open the file because the file format or file extension is not valid... ") 在此处输入图像描述

'excel5' is for xls ( 'exel2007' is for xlsx )

Hence, change the write to excel block to

$fetched->fromArray($exceldatas, null, 'A1', true);
$objWriter = PHPExcel_IOFactory::createWriter($readphpexcel, 'Excel2007');// Excel 2010
$objWriter->save("polimer_uzex.xlsx");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM