CaiWuXiTong/app/Support/CourierBills/StreamingWorkbook.php

195 lines
9.4 KiB
PHP

<?php
namespace App\Support\CourierBills;
use RuntimeException;
use ZipArchive;
/**
* 多工作表的低内存 XLSX 写出(和 App\Support\StreamingXlsxWriter 同一做法,多了工作表和表头加粗)。
*
* 行按顺序写进各表的临时文件,最后打包;内存占用与行数无关。字符串一律写成文本单元格,
* 长单号不会变成科学计数法。没有写过任何行的工作表不会出现在文件里。
*/
final class StreamingWorkbook
{
/** @var array<string,array{path:string,handle:resource,row:int,widths:array<int,int>}> */
private array $sheets = [];
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 = self::sheetName($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="1"' : '';
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 isEmpty(): bool
{
return $this->sheets === [];
}
/** @param resource $output */
public function writeTo($output): void
{
if ($this->sheets === []) {
$this->row('Sheet1', []);
}
$zipPath = tempnam(sys_get_temp_dir(), 'bill_zip_');
if ($zipPath === false) {
throw new RuntimeException('无法创建导出文件。');
}
try {
$zip = new ZipArchive();
if ($zip->open($zipPath, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== true) {
throw new RuntimeException('无法创建导出文件。');
}
$names = array_keys($this->sheets);
$contentTypes = '';
$workbook = '';
$relations = '';
foreach ($names as $i => $name) {
$n = $i + 1;
$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 = tempnam(sys_get_temp_dir(), 'bill_ws_');
$out = fopen((string) $sheetPath, 'wb');
$in = fopen($state['path'], 'rb');
fwrite($out, '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
. '<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">'
. '<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'] = (string) $sheetPath;
$zip->addFile((string) $sheetPath, '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($names) + 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', '<?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>');
$zip->close();
$handle = fopen($zipPath, 'rb');
stream_copy_to_stream($handle, $output);
fclose($handle);
} finally {
@unlink($zipPath);
}
}
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;
}
}