For more information about PHPEXCEL, I can't find a function that can replace input. & Nbsp; for example, I enter {name} and {age} in any lattice of an EXCEL template }. & nbsp; how to replace {name} with & nbsp; James, & nbsp; replace {age} with & nbsp; 20 & nbsp, thank you!
PHPEXCEL is very powerful, but I have been searching for it for a long time and cannot find the function that replaces input. For example, I enter {name} and {age} in any lattice of the EXCEL template }. how do I replace {name} with Michael Jacob and replace {age} with 20? After replacement, save it for user download.
(Currently, the examples I have seen are to locate D1 and A2. This is not the case)
Thank you. Share:
------ Solution --------------------
Each cell in EXCEL is independent, so it is also true in PHPEXCEL.
To reduce memory usage, PHPEXCEL does not read worksheets into the memory at a time. Therefore, it is inevitable to locate cells through columns.
Apply the template you entered
You only need to traverse the valid area in the worksheet and replace each template element.
------ Solution --------------------
include 'Plugin/PHPExcel/Classes/PHPExcel/IOFactory.php';
class fill_template {
var $startrow = 0;
function __construct($fn) {
$this->tpl = PHPExcel_IOFactory::load($fn);
$this->target = clone $this->tpl;
}
function add_data($ar) {
$sheet = $this->tpl->getActiveSheet();
$i = 0;
$mcol = $sheet->getHighestColumn();
foreach($sheet->getRowDimensions() as $y=>$row) {
for($x='A'; $x<=$mcol; $x++) {
$txt = trim($sheet->getCell($x.$y)->getValue());
if($txt && preg_match('/{(.+)}/', $txt, $match)) {
$txt = isset($ar[$match[1]]) ? iconv('gbk', 'utf-8', $ar[$match[1]]) : '';
}
$h = $y + $this->startrow;
$this->target->getActiveSheet()->getCell("$x$h")->setValue($txt);
$this->target->getActiveSheet()->duplicateStyle($sheet->getStyle("$x$y"), "$x$h");
}
}
foreach($sheet->getMergeCells() as $merge) {
$merge = preg_replace('/\d+/e',"$0+$this->startrow", $merge);