diff --git a/app/admin/common.php b/app/admin/common.php index 67dd7791..7ecd1a55 100644 --- a/app/admin/common.php +++ b/app/admin/common.php @@ -27,6 +27,47 @@ if (!function_exists('array_to_tree')) { } } +if (!function_exists('xlsx_reader')) { + /** + * 读取Excel数据 + * @param string $file Excel文件路径 + * @param int $initial_row 初始行 + * @param array $keys_map 列 -> 键 例:['A' => 'name', 'B' => 'age', 'C' => 'sex'] + * @return array + */ + function xlsx_reader(string $file, int $initial_row = 1, array $keys_map = []): array + { + $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader('Xlsx'); + + // 读取文件 + $spreadsheet = $reader->load($file); + + // 获取活动sheet + $sheet = $spreadsheet->getActiveSheet(); + + // 获取最大行 + $max_row = $sheet->getHighestRow(); + + // 获取最大列 + $max_col = $sheet->getHighestColumn(); + + $xlsx_data = []; + $first_col = ord('A'); + $last_col = ord($max_col); + for ($row = $initial_row; $row <= $max_row; $row++) { + for ($col = $first_col; $col <= $last_col; $col++) { + $key = $col_chr = chr($col); + if (!empty($keys_map)) { + $key = $keys_map[$col_chr] ?? $col_chr; + } + $xlsx_data[$row][$key] = $sheet->getCell($col_chr . $row)->getValue(); + } + } + + return $xlsx_data; + } +} + if (!function_exists('xlsx_writer')) { /** * 构建Excel数据 diff --git a/app/admin/controller/v1/ProductPurchaseLink.php b/app/admin/controller/v1/ProductPurchaseLink.php index 8f1fa73c..b60cf7af 100644 --- a/app/admin/controller/v1/ProductPurchaseLink.php +++ b/app/admin/controller/v1/ProductPurchaseLink.php @@ -8,7 +8,6 @@ use app\admin\model\v1\ProductModel; use app\admin\model\v1\ProductPurchaseLinkModel; use app\admin\model\v1\ProductPurchaseLinkPlatformModel; use app\admin\validate\v1\ProductPurchaseLinkValidate; -use PhpOffice\PhpSpreadsheet\IOFactory; use think\facade\Db; class ProductPurchaseLink @@ -118,26 +117,8 @@ class ProductPurchaseLink return error('上传文件不能超过20M'); } - $reader = IOFactory::createReader('Xlsx'); - - // 读取文件 - $spreadsheet = $reader->load($file->getRealPath()); - - // 获取活动sheet - $sheet = $spreadsheet->getActiveSheet(); - - // 获取行数 - $rows = $sheet->getHighestRow(); - // 从表格获取数据 - $xlsx_data = []; - for ($i=2; $i <= $rows; $i++) { - $xlsx_data[$i] = [ - 'spu' => $sheet->getCell('A' . $i)->getValue(), - 'platform' => $sheet->getCell('B' . $i)->getValue(), - 'link' => $sheet->getCell('C' . $i)->getValue(), - ]; - } + $xlsx_data = xlsx_reader($file->getRealPath(), 2, ['A' => 'spu', 'B' => 'platform', 'C' => 'link']); $platforms_name = array_unique(array_column($xlsx_data, 'platform')); $platforms_map = ProductPurchaseLinkPlatformModel::language(request()->lang_id)