使用PHP实现对Excel的文本替换操作


function xlsx_str_replace($file_tpl, $file_target, $data) {
copy($file_tpl, $file_target);
$sheet1 = 'xl/sharedStrings.xml';
$zip = new ZipArchive;
if ($zip->open($file_target, ZipArchive::CREATE) !== TRUE) {
return;
}
$stream = $zip->getStream($sheet1);
$str = stream_get_contents($stream);
fclose($stream);
foreach ($data as $k => $v) {
$str = str_replace('{' . $k . '}', $v, $str);
}
$zip->addFromString($sheet1, $str);
$zip->close();
}
$data = array();
$data['供方公司'] = '11111';
$data['需方公司'] = '22222';
xlsx_str_replace('tpl/4860.xlsx', '1.xlsx', $data);