CaiWuXiTong/app/Support/CourierBills/BillWorkbookReader.php

267 lines
10 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 PhpOffice\PhpSpreadsheet\IOFactory;
use RuntimeException;
use XMLReader;
use ZipArchive;
/**
* 快递账单文件逐行读取:xlsx 流式解析(不整表进内存),csv 逐行读取(自动识别 GBK),
* 老 xls 用 PhpSpreadsheet 读(快递很少发 xls,单文件限 20MB)。
*
* 每行返回「列下标 => 文本」的完整数组,含表头和标题行,由调用方找表头。
*/
final class BillWorkbookReader
{
/** @return Generator<string, Generator<int, array<int,string>>> 工作表名 => 行(行号 => 列) */
public function sheets(string $path, string $extension): Generator
{
$extension = strtolower($extension);
if ($extension === 'csv') {
yield 'csv' => $this->csvRows($path);
return;
}
if ($extension === 'xls') {
yield from $this->xlsSheets($path);
return;
}
$zip = new ZipArchive();
if ($zip->open($path) !== true) {
throw new RuntimeException('文件不是有效的 xlsx。');
}
try {
$shared = $this->sharedStrings($zip);
foreach ($this->worksheets($zip) as $name => $target) {
yield $name => $this->xlsxRows($path, $target, $shared);
}
} finally {
$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;
}
/** @return list<string> */
private function sharedStrings(ZipArchive $zip): array
{
if ($zip->locateName('xl/sharedStrings.xml') === false) {
return [];
}
$reader = new XMLReader();
$reader->XML((string) $zip->getFromName('xl/sharedStrings.xml'), 'UTF-8', LIBXML_NONET | LIBXML_COMPACT | LIBXML_PARSEHUGE);
$strings = [];
$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') {
$strings[] = (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();
return $strings;
}
/** @param list<string> $shared */
private function xlsxRows(string $path, string $target, array $shared): 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) {
$row[$column] = $type === 's' ? ($shared[(int) $value] ?? '') : trim($value);
}
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): 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): 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 trim($cell);
}, $row);
}
} finally {
fclose($handle);
}
}
private function xlsSheets(string $path): Generator
{
if (filesize($path) > 20 * 1024 * 1024) {
throw new RuntimeException('xls 文件超过 20MB,请另存为 xlsx 后上传。');
}
$reader = IOFactory::createReader('Xls');
$reader->setReadDataOnly(true);
$book = $reader->load($path);
try {
foreach ($book->getWorksheetIterator() as $sheet) {
$rows = [];
foreach ($sheet->getRowIterator() as $row) {
$cells = [];
foreach ($row->getCellIterator() as $cell) {
$cells[] = trim((string) $cell->getValue());
}
$rows[$row->getRowIndex()] = $cells;
}
yield $sheet->getTitle() => (static fn () => yield from $rows)();
}
} 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;
}
}