refactor: xlsx导入封装

This commit is contained in:
2025-02-20 16:48:48 +08:00
parent 59d7bfacad
commit 18a94ea6d2
2 changed files with 42 additions and 20 deletions

View File

@@ -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数据