}> */ private array $sheets = []; /** 加粗单元格用的样式序号(有原文件时是追加到原文件 styles.xml 里的那个)。 */ private int $boldStyle = 1; /** @var array{path:string,workbook:string,rels:string,styles:?string,stylesXml:?string,names:array}|null */ private ?array $base = null; /** @var array 原文件里要改名的表:原名 => 新名 */ private array $renames = []; /** @var list 排在原文件各表前面的新表(如「汇总」),其余新表排在原文件后面 */ private array $first = []; /** * 以这个原始 xlsx 为底:原文件的所有工作表原封不动,后面写的表追加在它后面。必须在写任何行之前调用。 * 文件不是普通 xlsx(xls、csv、带宏的、Strict 格式、打不开的)时返回 false,照旧生成新文件。 * * @return list|null 原文件的工作表名(按顺序);用不了时为 null */ public function base(string $path): ?array { if ($this->sheets !== [] || ! is_file($path)) { return null; } $zip = new ZipArchive(); if ($zip->open($path) !== true) { return null; } try { $root = self::dom($zip, '_rels/.rels'); $workbook = null; foreach ($root?->getElementsByTagNameNS(self::PKG_REL_NS, 'Relationship') ?? [] as $rel) { if (str_ends_with($rel->getAttribute('Type'), '/officeDocument')) { $workbook = ltrim($rel->getAttribute('Target'), '/'); } } $types = self::dom($zip, '[Content_Types].xml'); $book = $workbook === null ? null : self::dom($zip, $workbook); if ($types === null || $book === null || $book->documentElement->namespaceURI !== self::MAIN_NS || $book->getElementsByTagNameNS(self::MAIN_NS, 'sheets')->length !== 1) { return null; } foreach ($types->getElementsByTagNameNS(self::CT_NS, 'Override') as $override) { if (ltrim($override->getAttribute('PartName'), '/') === $workbook && ! str_contains($override->getAttribute('ContentType'), 'sheet.main+xml')) { return null; // 带宏的 / 模板,另存成 .xlsx 会打不开 } } $dir = dirname($workbook); $relsPath = ($dir === '.' ? '' : $dir . '/') . '_rels/' . basename($workbook) . '.rels'; $rels = self::dom($zip, $relsPath); if ($rels === null) { return null; } $styles = null; foreach ($rels->getElementsByTagNameNS(self::PKG_REL_NS, 'Relationship') as $rel) { if (str_ends_with($rel->getAttribute('Type'), '/styles')) { $target = $rel->getAttribute('Target'); $styles = str_starts_with($target, '/') ? ltrim($target, '/') : ($dir === '.' ? '' : $dir . '/') . $target; } } $stylesXml = null; $bold = 1; $styleDom = $styles === null ? null : self::dom($zip, $styles); if ($styles !== null && $styleDom === null) { return null; } if ($styleDom !== null) { $fonts = $styleDom->getElementsByTagNameNS(self::MAIN_NS, 'fonts')->item(0); $xfs = $styleDom->getElementsByTagNameNS(self::MAIN_NS, 'cellXfs')->item(0); if (! $fonts instanceof DOMElement || ! $xfs instanceof DOMElement) { return null; } $font = $styleDom->createElementNS(self::MAIN_NS, 'font'); $font->appendChild($styleDom->createElementNS(self::MAIN_NS, 'b')); $size = $styleDom->createElementNS(self::MAIN_NS, 'sz'); $size->setAttribute('val', '11'); $font->appendChild($size); $fonts->appendChild($font); $fontId = $fonts->getElementsByTagNameNS(self::MAIN_NS, 'font')->length - 1; $fonts->setAttribute('count', (string) ($fontId + 1)); $xf = $styleDom->createElementNS(self::MAIN_NS, 'xf'); foreach (['numFmtId' => '0', 'fontId' => (string) $fontId, 'fillId' => '0', 'borderId' => '0', 'xfId' => '0', 'applyFont' => '1'] as $key => $value) { $xf->setAttribute($key, $value); } $xfs->appendChild($xf); $bold = 0; foreach ($xfs->childNodes as $node) { $bold += $node instanceof DOMElement && $node->localName === 'xf' ? 1 : 0; } $bold--; $xfs->setAttribute('count', (string) ($bold + 1)); $stylesXml = (string) $styleDom->saveXML(); } $names = []; foreach ($book->getElementsByTagNameNS(self::MAIN_NS, 'sheet') as $sheet) { $names[] = $sheet->getAttribute('name'); } } catch (Throwable) { return null; } finally { $zip->close(); } $this->boldStyle = $bold; $this->base = ['path' => $path, 'workbook' => $workbook, 'rels' => $relsPath, 'styles' => $styleDom === null ? null : $styles, 'stylesXml' => $stylesXml, 'names' => array_fill_keys(array_map('mb_strtolower', $names), true)]; return $names; } private static function dom(ZipArchive $zip, string $name): ?DOMDocument { $xml = $zip->getFromName($name); if ($xml === false) { return null; } $dom = new DOMDocument(); return $dom->loadXML($xml, LIBXML_NONET | LIBXML_PARSEHUGE) ? $dom : null; } public function __destruct() { foreach ($this->sheets as $sheet) { if (is_resource($sheet['handle'])) { fclose($sheet['handle']); } @unlink($sheet['path']); } } /** * 给原文件(base())里的表改名,如「Sheet1」→「厂家账单」。只改表名和引用这张表的公式(单元格公式、条件格式、数据验证、 * 图表、定义的名称),单元格内容和格式不动。必须在 base() 之后、写任何行之前调用。 * * @param array $renames 原名 => 新名 */ public function renameBase(array $renames): void { if ($this->base === null || $this->sheets !== []) { return; } $names = array_keys($this->base['names']); $taken = []; $result = []; foreach ($renames as $old => $new) { $old = (string) $old; $new = self::sheetName((string) $new); if ($new === '' || $old === $new || ! isset($this->base['names'][mb_strtolower($old)]) || isset($taken[mb_strtolower($new)])) { continue; } $taken[mb_strtolower($new)] = true; $result[$old] = $new; } // 没改名的表名不能和新名撞 foreach ($names as $name) { if (! in_array($name, array_map('mb_strtolower', array_keys($result)), true) && isset($taken[$name])) { return; } } $this->renames = $result; $kept = array_diff($names, array_map('mb_strtolower', array_keys($result))); $this->base['names'] = array_fill_keys([...$kept, ...array_keys($taken)], true); } /** 这些新表排在最前面(在原文件的表前面),打开文件时停在第一张。没有原文件时按写入先后排。 @param list $sheets */ public function putFirst(array $sheets): void { $this->first = array_values(array_unique(array_map(fn (string $sheet): string => $this->nameOf($sheet), $sheets))); } /** @param list $cells */ public function row(string $sheet, array $cells, bool $bold = false): void { $sheet = $this->nameOf($sheet); if (! isset($this->sheets[$sheet])) { $path = tempnam(sys_get_temp_dir(), 'bill_sheet_'); $handle = $path === false ? false : fopen($path, 'wb'); if ($handle === false) { throw new RuntimeException('无法创建导出临时文件。'); } $this->sheets[$sheet] = ['path' => $path, 'handle' => $handle, 'row' => 0, 'widths' => []]; } $state = &$this->sheets[$sheet]; $number = ++$state['row']; $xml = ''; foreach (array_values($cells) as $index => $value) { if ($value === null || $value === '') { continue; } $reference = self::column($index + 1) . $number; $style = $bold ? ' s="' . $this->boldStyle . '"' : ''; if ($value instanceof XlsxFormula) { $cached = $value->cached; $xml .= '' . self::escape($value->expression) . '' . (is_int($cached) || is_float($cached) ? '' . self::number($cached) . '' : (is_string($cached) ? '' . self::escape($cached) . '' : '')) . ''; $width = is_int($cached) || is_float($cached) ? strlen(self::number($cached)) : 8; } elseif (is_int($value) || is_float($value)) { $xml .= '' . self::number($value) . ''; $width = strlen(self::number($value)); } else { $text = (string) $value; $xml .= '' . self::escape($text) . ''; $width = mb_strwidth($text); } if ($number <= 200) { $state['widths'][$index] = max($state['widths'][$index] ?? 8, min($width + 2, 40)); } } fwrite($state['handle'], $xml . ''); } /** 写进文件时这张表实际的名字:和原文件里的表重名时加「(系统)」。 */ public function nameOf(string $sheet): string { $sheet = self::sheetName($sheet); if ($this->base !== null) { for ($n = 1, $name = $sheet; isset($this->base['names'][mb_strtolower($sheet)]); $n++) { $suffix = '(系统' . ($n > 1 ? $n : '') . ')'; $sheet = self::sheetName(mb_substr($name, 0, 31 - mb_strlen($suffix)) . $suffix); } } return $sheet; } public function isEmpty(): bool { return $this->sheets === []; } /** @param resource $output */ public function writeTo($output): void { if ($this->sheets === [] && $this->base === null) { $this->row('Sheet1', []); } $zipPath = tempnam(sys_get_temp_dir(), 'bill_zip_'); if ($zipPath === false) { throw new RuntimeException('无法创建导出文件。'); } try { if ($this->base !== null) { $this->packOnBase($zipPath); } else { $this->packNew($zipPath); } $handle = fopen($zipPath, 'rb'); stream_copy_to_stream($handle, $output); fclose($handle); } finally { @unlink($zipPath); } } /** 把一张表的行包成完整的 worksheet XML 文件,返回文件路径。 */ private function finishSheet(string $name): string { $state = $this->sheets[$name]; fclose($state['handle']); $cols = ''; foreach ($state['widths'] as $index => $width) { $cols .= ''; } $sheetPath = (string) tempnam(sys_get_temp_dir(), 'bill_ws_'); $out = fopen($sheetPath, 'wb'); $in = fopen($state['path'], 'rb'); fwrite($out, '' . '' . '' . ($cols !== '' ? '' . $cols . '' : '') . ''); stream_copy_to_stream($in, $out); fwrite($out, ''); fclose($in); fclose($out); @unlink($state['path']); $this->sheets[$name]['path'] = $sheetPath; return $sheetPath; } /** 原文件原样复制,只在 workbook.xml / 关系 / 内容类型 / styles.xml 里追加新表,原有工作表的 XML 一个字节都不改。 */ private function packOnBase(string $zipPath): void { if (! copy($this->base['path'], $zipPath)) { throw new RuntimeException('无法创建导出文件。'); } $zip = new ZipArchive(); if ($zip->open($zipPath) !== true) { throw new RuntimeException('无法创建导出文件。'); } $book = self::dom($zip, $this->base['workbook']); $rels = self::dom($zip, $this->base['rels']); $types = self::dom($zip, '[Content_Types].xml'); $sheetsNode = $book->getElementsByTagNameNS(self::MAIN_NS, 'sheets')->item(0); if ($this->renames !== []) { $this->applyRenames($zip, $book); } $maxId = 0; foreach ($book->getElementsByTagNameNS(self::MAIN_NS, 'sheet') as $sheet) { $maxId = max($maxId, (int) $sheet->getAttribute('sheetId')); } $dir = dirname($this->base['workbook']); $prefix = $dir === '.' ? '' : $dir . '/'; $relationshipIds = []; foreach ($rels->getElementsByTagNameNS(self::PKG_REL_NS, 'Relationship') as $relationship) { $relationshipIds[$relationship->getAttribute('Id')] = true; } $n = 0; $originalCount = $book->getElementsByTagNameNS(self::MAIN_NS, 'sheet')->length; $firstNodes = []; foreach (array_keys($this->sheets) as $name) { do { $n++; $part = 'worksheets/cbr_sheet' . $n . '.xml'; $relationshipId = 'rIdCbr' . $n; } while (isset($relationshipIds[$relationshipId]) || $zip->locateName($prefix . $part, ZipArchive::FL_NOCASE) !== false); $zip->addFile($this->finishSheet($name), $prefix . $part); $sheet = $book->createElementNS(self::MAIN_NS, 'sheet'); $sheet->setAttribute('name', $name); $sheet->setAttribute('sheetId', (string) ($maxId + $n)); $sheet->setAttributeNS(self::REL_NS, 'r:id', $relationshipId); $sheetsNode->appendChild($sheet); if (in_array($name, $this->first, true)) { $firstNodes[array_search($name, $this->first, true)] = $sheet; } $rel = $rels->createElementNS(self::PKG_REL_NS, 'Relationship'); $rel->setAttribute('Id', $relationshipId); $rel->setAttribute('Type', self::REL_NS . '/worksheet'); $rel->setAttribute('Target', $part); $rels->documentElement->appendChild($rel); $override = $types->createElementNS(self::CT_NS, 'Override'); $override->setAttribute('PartName', '/' . $prefix . $part); $override->setAttribute('ContentType', 'application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml'); $types->documentElement->appendChild($override); } if ($firstNodes !== []) { $this->moveToFront($zip, $book, $sheetsNode, $firstNodes, $originalCount); } if ($this->base['styles'] === null) { // 原文件没有 styles.xml:补一份只含普通和加粗两种样式的 $styleNumber = 0; do { $styleNumber++; $stylePart = 'styles_cbr' . $styleNumber . '.xml'; $styleRelationship = 'rIdCbrStyles' . $styleNumber; } while (isset($relationshipIds[$styleRelationship]) || $zip->locateName($prefix . $stylePart, ZipArchive::FL_NOCASE) !== false); $zip->addFromString($prefix . $stylePart, self::STYLES); $rel = $rels->createElementNS(self::PKG_REL_NS, 'Relationship'); $rel->setAttribute('Id', $styleRelationship); $rel->setAttribute('Type', self::REL_NS . '/styles'); $rel->setAttribute('Target', $stylePart); $rels->documentElement->appendChild($rel); $override = $types->createElementNS(self::CT_NS, 'Override'); $override->setAttribute('PartName', '/' . $prefix . $stylePart); $override->setAttribute('ContentType', 'application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml'); $types->documentElement->appendChild($override); } else { $zip->addFromString($this->base['styles'], (string) $this->base['stylesXml']); } $zip->addFromString($this->base['workbook'], (string) $book->saveXML()); $zip->addFromString($this->base['rels'], (string) $rels->saveXML()); $zip->addFromString('[Content_Types].xml', (string) $types->saveXML()); if (! $zip->close()) { throw new RuntimeException('无法创建导出文件。'); } } /** @return list 写进文件的表顺序:putFirst 的在前 */ private function orderedNames(): array { $first = array_values(array_filter($this->first, fn (string $name): bool => isset($this->sheets[$name]))); return [...$first, ...array_values(array_diff(array_keys($this->sheets), $first))]; } /** * 把新表挪到原文件各表前面:定义名称里按位置记的 localSheetId 跟着往后移,打开时停在第一张, * 原文件里「选中的表」标记去掉(不然打开时会同时选中两张表)。 * * @param array $nodes 位置 => 新表的 sheet 元素 */ private function moveToFront(ZipArchive $zip, DOMDocument $book, \DOMNode $sheetsNode, array $nodes, int $originalCount): void { ksort($nodes); $anchor = $sheetsNode->firstChild; while ($anchor !== null && ! ($anchor instanceof DOMElement && $anchor->localName === 'sheet')) { $anchor = $anchor->nextSibling; } foreach ($nodes as $node) { $sheetsNode->insertBefore($node, $anchor); } $shift = count($nodes); foreach ($book->getElementsByTagNameNS(self::MAIN_NS, 'definedName') as $defined) { if ($defined->hasAttribute('localSheetId') && (int) $defined->getAttribute('localSheetId') < $originalCount) { $defined->setAttribute('localSheetId', (string) ((int) $defined->getAttribute('localSheetId') + $shift)); } } foreach ($book->getElementsByTagNameNS(self::MAIN_NS, 'workbookView') as $view) { $view->setAttribute('activeTab', '0'); $view->setAttribute('firstSheet', '0'); } if ($book->getElementsByTagNameNS(self::MAIN_NS, 'workbookView')->length === 0) { $views = $book->createElementNS(self::MAIN_NS, 'bookViews'); $view = $book->createElementNS(self::MAIN_NS, 'workbookView'); $view->setAttribute('activeTab', '0'); $views->appendChild($view); $book->documentElement->insertBefore($views, $sheetsNode); } for ($i = 0; $i < $zip->numFiles; $i++) { $part = (string) $zip->getNameIndex($i); if (! preg_match('#^xl/worksheets/[^/]+\.xml$#i', $part) || str_contains($part, 'cbr_sheet')) { continue; } $xml = $zip->getFromIndex($i); if ($xml !== false && str_contains($xml, 'tabSelected="1"')) { $zip->addFromString($part, str_replace(' tabSelected="1"', '', $xml)); } } } /** 原文件表改名:workbook.xml 里的表名、定义的名称,和各部件里引用这些表的公式。 */ private function applyRenames(ZipArchive $zip, DOMDocument $book): void { foreach ($book->getElementsByTagNameNS(self::MAIN_NS, 'sheet') as $sheet) { $name = $sheet->getAttribute('name'); if (isset($this->renames[$name])) { $sheet->setAttribute('name', $this->renames[$name]); } } foreach ($book->getElementsByTagNameNS(self::MAIN_NS, 'definedName') as $defined) { $text = self::renameInFormula($defined->textContent, $this->renames); if ($text !== $defined->textContent) { while ($defined->firstChild !== null) { $defined->removeChild($defined->firstChild); } $defined->appendChild($book->createTextNode($text)); } } $escaped = []; foreach ($this->renames as $old => $new) { $escaped[self::escape($old)] = self::escape($new); } for ($i = 0; $i < $zip->numFiles; $i++) { $part = (string) $zip->getNameIndex($i); if (! preg_match('#^xl/(worksheets|charts|chartsheets)/[^/]+\.xml$#i', $part)) { continue; } $xml = $zip->getFromIndex($i); if ($xml === false || ! array_filter(array_keys($escaped), static fn (string $old): bool => str_contains($xml, $old))) { continue; } $changed = preg_replace_callback('#(<((?:\w+:)?(?:f|formula\d?))(?:\s[^>]*)?(?)(.*?)()#s', static fn (array $m): string => $m[1] . self::renameInFormula($m[3], $escaped) . $m[4], $xml); if (is_string($changed) && $changed !== $xml) { $zip->addFromString($part, $changed); } } } /** 公式里 Sheet1!A1、'Sheet 1'!A1 这样的表引用换成新表名(新名一律加单引号)。 */ private static function renameInFormula(string $formula, array $renames): string { foreach ($renames as $old => $new) { $quotedNew = "'" . str_replace("'", "''", (string) $new) . "'!"; $formula = str_replace("'" . str_replace("'", "''", (string) $old) . "'!", $quotedNew, $formula); $formula = preg_replace('/(?' . '' . '' . '' . '' . '' . '' . '' . ''; private function packNew(string $zipPath): void { $zip = new ZipArchive(); if ($zip->open($zipPath, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== true) { throw new RuntimeException('无法创建导出文件。'); } $contentTypes = ''; $workbook = ''; $relations = ''; foreach ($this->orderedNames() as $i => $name) { $n = $i + 1; $zip->addFile($this->finishSheet($name), 'xl/worksheets/sheet' . $n . '.xml'); $contentTypes .= ''; $workbook .= ''; $relations .= ''; } $styles = count($this->sheets) + 1; $zip->addFromString('[Content_Types].xml', '' . '' . '' . '' . '' . '' . $contentTypes . ''); $zip->addFromString('_rels/.rels', '' . '' . '' . ''); $zip->addFromString('xl/workbook.xml', '' . '' . '' . $workbook . ''); $zip->addFromString('xl/_rels/workbook.xml.rels', '' . '' . $relations . '' . ''); $zip->addFromString('xl/styles.xml', self::STYLES); $zip->close(); } private static function sheetName(string $name): string { $name = str_replace(['\\', '/', '?', '*', '[', ']', ':'], '-', $name); return mb_substr($name === '' ? 'Sheet' : $name, 0, 31); } private static function number(int|float $value): string { if (is_int($value)) { return (string) $value; } if (! is_finite($value)) { return '0'; } $text = rtrim(rtrim(sprintf('%.10F', $value), '0'), '.'); return ($text === '' || $text === '-' || $text === '-0') ? '0' : $text; } private static function escape(string $value): string { if (! mb_check_encoding($value, 'UTF-8')) { $value = mb_convert_encoding($value, 'UTF-8', 'UTF-8'); } $value = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F]/u', '', $value) ?? $value; return htmlspecialchars($value, ENT_QUOTES | ENT_XML1, 'UTF-8'); } private static function column(int $index): string { $name = ''; while ($index > 0) { $index--; $name = chr(65 + ($index % 26)) . $name; $index = intdiv($index, 26); } return $name; } }