426 lines
20 KiB
PHP
426 lines
20 KiB
PHP
<?php
|
||
|
||
namespace App\Support\CourierBills;
|
||
|
||
use DOMDocument;
|
||
use DOMElement;
|
||
use RuntimeException;
|
||
use Throwable;
|
||
use ZipArchive;
|
||
|
||
/**
|
||
* 多工作表的低内存 XLSX 写出(和 App\Support\StreamingXlsxWriter 同一做法,多了工作表和表头加粗)。
|
||
*
|
||
* 行按顺序写进各表的临时文件,最后打包;内存占用与行数无关。字符串一律写成文本单元格,
|
||
* 长单号不会变成科学计数法。没有写过任何行的工作表不会出现在文件里。
|
||
*
|
||
* 可以先用 base() 指定一个原始 xlsx:导出文件就是这个原文件本身(每张表的内容、格式、公式、合并单元格都不动),
|
||
* 写出的工作表追加在它后面。
|
||
*/
|
||
final class StreamingWorkbook
|
||
{
|
||
private const MAIN_NS = 'http://schemas.openxmlformats.org/spreadsheetml/2006/main';
|
||
private const REL_NS = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships';
|
||
private const PKG_REL_NS = 'http://schemas.openxmlformats.org/package/2006/relationships';
|
||
private const CT_NS = 'http://schemas.openxmlformats.org/package/2006/content-types';
|
||
|
||
/** @var array<string,array{path:string,handle:resource,row:int,widths:array<int,int>}> */
|
||
private array $sheets = [];
|
||
|
||
/** 加粗单元格用的样式序号(有原文件时是追加到原文件 styles.xml 里的那个)。 */
|
||
private int $boldStyle = 1;
|
||
|
||
/** @var array{path:string,workbook:string,rels:string,styles:?string,stylesXml:?string,names:array<string,true>}|null */
|
||
private ?array $base = null;
|
||
|
||
/**
|
||
* 以这个原始 xlsx 为底:原文件的所有工作表原封不动,后面写的表追加在它后面。必须在写任何行之前调用。
|
||
* 文件不是普通 xlsx(xls、csv、带宏的、Strict 格式、打不开的)时返回 false,照旧生成新文件。
|
||
*
|
||
* @return list<string>|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<string|int|float|null> $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 = '<row r="' . $number . '">';
|
||
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 .= '<c r="' . $reference . '"' . $style . '><v>' . self::number($value) . '</v></c>';
|
||
$width = strlen(self::number($value));
|
||
} else {
|
||
$text = (string) $value;
|
||
$xml .= '<c r="' . $reference . '"' . $style . ' t="inlineStr"><is><t xml:space="preserve">'
|
||
. self::escape($text) . '</t></is></c>';
|
||
$width = mb_strwidth($text);
|
||
}
|
||
if ($number <= 200) {
|
||
$state['widths'][$index] = max($state['widths'][$index] ?? 8, min($width + 2, 40));
|
||
}
|
||
}
|
||
fwrite($state['handle'], $xml . '</row>');
|
||
}
|
||
|
||
/** 写进文件时这张表实际的名字:和原文件里的表重名时加「(系统)」。 */
|
||
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 .= '<col min="' . ($index + 1) . '" max="' . ($index + 1) . '" width="' . $width . '" customWidth="1"/>';
|
||
}
|
||
$sheetPath = (string) tempnam(sys_get_temp_dir(), 'bill_ws_');
|
||
$out = fopen($sheetPath, 'wb');
|
||
$in = fopen($state['path'], 'rb');
|
||
fwrite($out, '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
|
||
. '<worksheet xmlns="' . self::MAIN_NS . '">'
|
||
. '<sheetViews><sheetView workbookViewId="0"><pane ySplit="1" topLeftCell="A2" activePane="bottomLeft" state="frozen"/></sheetView></sheetViews>'
|
||
. ($cols !== '' ? '<cols>' . $cols . '</cols>' : '') . '<sheetData>');
|
||
stream_copy_to_stream($in, $out);
|
||
fwrite($out, '</sheetData></worksheet>');
|
||
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 = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
|
||
. '<styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">'
|
||
. '<fonts count="2"><font><sz val="11"/><name val="Calibri"/></font><font><b/><sz val="11"/><name val="Calibri"/></font></fonts>'
|
||
. '<fills count="2"><fill><patternFill patternType="none"/></fill><fill><patternFill patternType="gray125"/></fill></fills>'
|
||
. '<borders count="1"><border/></borders>'
|
||
. '<cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellStyleXfs>'
|
||
. '<cellXfs count="2"><xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"/>'
|
||
. '<xf numFmtId="0" fontId="1" fillId="0" borderId="0" xfId="0" applyFont="1"/></cellXfs>'
|
||
. '</styleSheet>';
|
||
|
||
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 .= '<Override PartName="/xl/worksheets/sheet' . $n . '.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>';
|
||
$workbook .= '<sheet name="' . self::escape($name) . '" sheetId="' . $n . '" r:id="rId' . $n . '"/>';
|
||
$relations .= '<Relationship Id="rId' . $n . '" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet' . $n . '.xml"/>';
|
||
}
|
||
$styles = count($this->sheets) + 1;
|
||
$zip->addFromString('[Content_Types].xml', '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
|
||
. '<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">'
|
||
. '<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>'
|
||
. '<Default Extension="xml" ContentType="application/xml"/>'
|
||
. '<Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/>'
|
||
. '<Override PartName="/xl/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"/>'
|
||
. $contentTypes . '</Types>');
|
||
$zip->addFromString('_rels/.rels', '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
|
||
. '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">'
|
||
. '<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/>'
|
||
. '</Relationships>');
|
||
$zip->addFromString('xl/workbook.xml', '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
|
||
. '<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">'
|
||
. '<sheets>' . $workbook . '</sheets></workbook>');
|
||
$zip->addFromString('xl/_rels/workbook.xml.rels', '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
|
||
. '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">' . $relations
|
||
. '<Relationship Id="rId' . $styles . '" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/>'
|
||
. '</Relationships>');
|
||
$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;
|
||
}
|
||
}
|