CaiWuXiTong/app/Support/CourierBills/BillWorkbookReader.php
limeng e6b9775a24 快递账单支持合并导出、原始运费表和四位金额 (#1544)
按 0006、0007、0008 顺序整合;账单相关测试及隔离 MariaDB 迁移验证通过。
2026-11-28 11:31:38 +08:00

311 lines
13 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace App\Support\CourierBills;
use Generator;
use PDO;
use PDOStatement;
use PhpOffice\PhpSpreadsheet\Reader\IReadFilter;
use PhpOffice\PhpSpreadsheet\IOFactory;
use RuntimeException;
use XMLReader;
use ZipArchive;
/**
* 快递账单文件逐行读取:xlsx 流式解析(不整表进内存),csv 逐行读取(自动识别 GBK),
* 老 xls 用 PhpSpreadsheet 分块读取(单文件限 20MB)。
*
* 每行返回「列下标 => 文本」的完整数组,含表头和标题行,由调用方找表头。
*/
final class BillWorkbookReader
{
/** @return Generator<string, Generator<int, array<int,string>>> 工作表名 => 行(行号 => 列) */
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<string,string> 工作表名 => 包内路径(按工作簿顺序) */
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;去掉末尾可能被截断的半个汉字再判断编码。
$sample = strlen($head) === 65536 ? substr($head, 0, -4) : $head;
$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<int,string> $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;
}
}