文本」的完整数组,含表头和标题行,由调用方找表头。 */ final class BillWorkbookReader { /** @return Generator>> 工作表名 => 行(行号 => 列) */ public function sheets(string $path, string $extension, bool $preserveValues = false): Generator { $extension = strtolower($extension); if ($extension === 'csv') { yield 'csv' => $this->csvRows($path, $preserveValues); return; } if ($extension === 'xls') { yield from $this->xlsSheets($path, $preserveValues); return; } $zip = new ZipArchive(); if ($zip->open($path) !== true) { throw new RuntimeException('文件不是有效的 xlsx。'); } $stringsPath = tempnam(sys_get_temp_dir(), 'bill_strings_'); if ($stringsPath === false) { $zip->close(); throw new RuntimeException('无法创建账单读取临时文件。'); } try { $shared = $this->sharedStrings($path, $zip, $stringsPath); foreach ($this->worksheets($zip) as $name => $target) { yield $name => $this->xlsxRows($path, $target, $shared, $preserveValues); } } finally { $shared = null; @unlink($stringsPath); $zip->close(); } } /** @return array 工作表名 => 包内路径(按工作簿顺序) */ private function worksheets(ZipArchive $zip): array { $workbook = (string) $zip->getFromName('xl/workbook.xml'); $relations = (string) $zip->getFromName('xl/_rels/workbook.xml.rels'); $targets = []; if (preg_match_all('/<(?:\w+:)?Relationship\b([^>]*)\/?>/', $relations, $rels)) { foreach ($rels[1] as $attributes) { if (preg_match('/\bId="([^"]+)"/', $attributes, $id) && preg_match('/\bTarget="([^"]+)"/', $attributes, $target)) { $path = ltrim(html_entity_decode($target[1], ENT_QUOTES | ENT_XML1, 'UTF-8'), '/'); $targets[$id[1]] = str_starts_with($path, 'xl/') ? $path : 'xl/' . $path; } } } $sheets = []; if (preg_match_all('/<(?:\w+:)?sheet\b([^>]*)\/?>/', $workbook, $matches)) { foreach ($matches[1] as $attributes) { if (preg_match('/\bname="([^"]*)"/', $attributes, $name) && preg_match('/\br:id="([^"]+)"/', $attributes, $id) && isset($targets[$id[1]]) && ! preg_match('/\bstate="(hidden|veryHidden)"/', $attributes)) { $sheets[html_entity_decode($name[1], ENT_QUOTES | ENT_XML1, 'UTF-8')] = $targets[$id[1]]; } } } return $sheets; } /** 共享字符串逐条存临时 SQLite,避免大量不同单号把整张字符串表留在内存。 */ private function sharedStrings(string $path, ZipArchive $zip, string $stringsPath): ?PDOStatement { if ($zip->locateName('xl/sharedStrings.xml') === false) { return null; } $reader = new XMLReader(); $reader->open('zip://' . $path . '#xl/sharedStrings.xml', 'UTF-8', LIBXML_NONET | LIBXML_COMPACT | LIBXML_PARSEHUGE); $db = new PDO('sqlite:' . $stringsPath); $db->exec('PRAGMA cache_size=-2048'); $db->exec('CREATE TABLE strings (id INTEGER PRIMARY KEY, value TEXT NOT NULL)'); $db->beginTransaction(); $insert = $db->prepare('INSERT INTO strings VALUES (?, ?)'); $index = 0; $current = null; $inPhonetic = false; while ($reader->read()) { if ($reader->nodeType === XMLReader::ELEMENT) { if ($reader->localName === 'si') { $current = ''; } elseif ($reader->localName === 'rPh') { $inPhonetic = ! $reader->isEmptyElement; } } elseif ($reader->nodeType === XMLReader::END_ELEMENT) { if ($reader->localName === 'si') { $insert->execute([$index++, (string) $current]); $current = null; } elseif ($reader->localName === 'rPh') { $inPhonetic = false; } } elseif (($reader->nodeType === XMLReader::TEXT || $reader->nodeType === XMLReader::SIGNIFICANT_WHITESPACE) && $current !== null && ! $inPhonetic) { $current .= $reader->value; } } $reader->close(); $db->commit(); return $db->prepare('SELECT value FROM strings WHERE id = ?'); } private function xlsxRows(string $path, string $target, ?PDOStatement $shared, bool $preserveValues): Generator { $reader = new XMLReader(); if (! $reader->open('zip://' . $path . '#' . $target, 'UTF-8', LIBXML_NONET | LIBXML_COMPACT | LIBXML_PARSEHUGE)) { throw new RuntimeException('无法读取工作表。'); } try { $row = null; $rowNumber = 0; $column = -1; $type = null; $value = ''; $inValue = false; while ($reader->read()) { if ($reader->nodeType === XMLReader::ELEMENT) { switch ($reader->localName) { case 'row': $rowNumber = (int) ($reader->getAttribute('r') ?: $rowNumber + 1); $row = []; $column = -1; if ($reader->isEmptyElement) { yield $rowNumber => []; $row = null; } break; case 'c': $column = self::columnIndex($reader->getAttribute('r'), $column + 1); $type = $reader->getAttribute('t'); $value = ''; if ($reader->isEmptyElement && $row !== null) { $row[$column] = ''; } break; case 'v': case 't': $inValue = ! $reader->isEmptyElement; break; case 'rPh': if (! $reader->isEmptyElement) { $reader->next(); } break; } } elseif ($reader->nodeType === XMLReader::END_ELEMENT) { switch ($reader->localName) { case 'v': case 't': $inValue = false; break; case 'c': if ($row !== null) { if ($type === 's') { $shared?->execute([(int) $value]); $cell = $shared?->fetchColumn(); $cell = $cell === false || $cell === null ? '' : (string) $cell; } else { $cell = $preserveValues ? $value : trim($value); if ($preserveValues && ($type === null || $type === 'n') && is_numeric($cell)) { $cell = (float) $cell; } } $row[$column] = $cell; } break; case 'row': if ($row !== null) { yield $rowNumber => self::dense($row); } $row = null; break; } } elseif ($inValue && ($reader->nodeType === XMLReader::TEXT || $reader->nodeType === XMLReader::SIGNIFICANT_WHITESPACE || $reader->nodeType === XMLReader::CDATA)) { $value .= $reader->value; } } } finally { $reader->close(); } } private function csvRows(string $path, bool $preserveValues): Generator { $handle = fopen($path, 'rb'); if ($handle === false) { throw new RuntimeException('无法读取 CSV 文件。'); } try { $head = (string) fread($handle, 65536); rewind($handle); // 只用前 64KB 中的完整行判断编码,避免从汉字中间截断。 $lineEnd = strlen($head) === 65536 ? strrpos($head, "\n") : false; $sample = $lineEnd === false ? $head : substr($head, 0, $lineEnd + 1); $gbk = $sample !== '' && ! mb_check_encoding($sample, 'UTF-8'); $line = 0; while (($row = fgetcsv($handle, 0, ',', '"', '')) !== false) { $line++; if ($row === [null]) { yield $line => []; continue; } yield $line => array_map(static function ($cell) use ($gbk, $line, $preserveValues): string { $cell = (string) $cell; if ($gbk) { $cell = (string) mb_convert_encoding($cell, 'UTF-8', 'GB18030'); } if ($line === 1) { $cell = preg_replace('/^\xEF\xBB\xBF/', '', $cell) ?? $cell; } return $preserveValues ? $cell : trim($cell); }, $row); } } finally { fclose($handle); } } private function xlsSheets(string $path, bool $preserveValues): Generator { if (filesize($path) > 20 * 1024 * 1024) { throw new RuntimeException('xls 文件超过 20MB,请另存为 xlsx 后上传。'); } $reader = IOFactory::createReader('Xls'); $reader->setReadDataOnly(true); foreach ($reader->listWorksheetInfo($path) as $info) { yield $info['worksheetName'] => $this->xlsRows($path, $info, $preserveValues); } } private function xlsRows(string $path, array $info, bool $preserveValues): Generator { $reader = IOFactory::createReader('Xls'); $reader->setReadDataOnly(true); $reader->setLoadSheetsOnly([$info['worksheetName']]); for ($start = 1; $start <= $info['totalRows']; $start += 500) { $end = min($start + 499, $info['totalRows']); $reader->setReadFilter(new class($start, $end) implements IReadFilter { public function __construct(private int $start, private int $end) {} public function readCell($columnAddress, $row, $worksheetName = ''): bool { return $row >= $this->start && $row <= $this->end; } }); $book = $reader->load($path); try { $sheet = $book->getSheet(0); for ($number = $start; $number <= $end; $number++) { $cells = []; for ($column = 1; $column <= $info['totalColumns']; $column++) { $cell = $sheet->getCell([$column, $number]); $value = $cell->isFormula() ? $cell->getOldCalculatedValue() : $cell->getValue(); $cells[] = $preserveValues ? $value : trim((string) $value); } yield $number => $cells; } } finally { $book->disconnectWorksheets(); } } } /** @param array $row */ private static function dense(array $row): array { if ($row === []) { return []; } $out = array_fill(0, max(array_keys($row)) + 1, ''); return array_replace($out, $row); } private static function columnIndex(?string $reference, int $fallback): int { if ($reference === null || ! preg_match('/^([A-Z]+)/i', $reference, $m)) { return $fallback; } $index = 0; foreach (str_split(strtoupper($m[1])) as $letter) { $index = $index * 26 + ord($letter) - 64; } return $index - 1; } }