}> */ 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; /** * 以这个原始 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']); } } /** @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 (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); $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; 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); $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 ($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('无法创建导出文件。'); } } private const STYLES = '' . '' . '' . '' . '' . '' . '' . '' . ''; 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 (array_keys($this->sheets) 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; } }