PhpSpreadsheetImport.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. <?php
  2. namespace app\common\util;
  3. use PhpOffice\PhpSpreadsheet\Exception;
  4. use PhpOffice\PhpSpreadsheet\IOFactory;
  5. use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
  6. /**
  7. * Excel表格功能封装类
  8. */
  9. class PhpSpreadsheetImport
  10. {
  11. /**
  12. * 读取表格数据
  13. * @param string $path 路径
  14. * @param int $sheetIndex 工作簿索引
  15. * @param array $field 初始化数组键名
  16. * @param int $row 从第几行开始读
  17. * @param string $scene
  18. * @return array
  19. */
  20. public static function readData(string $path, array $field = [], int $row = 2, int $sheetIndex = 0, string $scene = 'excel'): array
  21. {
  22. try {
  23. // 创建读操作对象
  24. $reader = IOFactory::createReader('Xlsx');
  25. // 忽略任何格式的信息
  26. $reader->setReadDataOnly(true);
  27. // 打开文件、载入excel表格
  28. $spreadsheet = $reader->load($path);
  29. // 获取活动工作薄
  30. $sheet = $spreadsheet->getSheet($sheetIndex);
  31. // 返回表格数据
  32. return self::getCellData($row, $sheet, $field);
  33. } catch (\Exception $e) {
  34. // 有异常发生
  35. return ['code' => $e->getCode(), 'errMsg' => $e->getMessage()];
  36. }
  37. }
  38. /**
  39. * 获取单元格数据
  40. * @param $row
  41. * @param object $sheet
  42. * @param array $field
  43. * @return array
  44. * @throws Exception
  45. */
  46. private static function getCellData($row, object $sheet, array $field):array
  47. {
  48. # 获取最高列 返回字母 如: C
  49. $highestColumn = $sheet->getHighestColumn();
  50. # 获取最大行 返回数字 如: 4
  51. $highestRow = $sheet->getHighestRow();
  52. # 列数 改为数字显示
  53. $highestColumnIndex = Coordinate::columnIndexFromString($highestColumn);
  54. $data = [];
  55. // 从第二行开始读取数据
  56. for ($row; $row <= $highestRow; $row++) {
  57. $build = [];
  58. // 从第一列读取数据
  59. for ($col = 1; $col <= $highestColumnIndex; $col++) {
  60. // 'A' 对应的ASCII码十进制为 64
  61. // 将ASCII值转为字符
  62. $chr = chr(64 + $col);
  63. // 列转为数据库字段名
  64. $key = $field[$chr] ?? $chr;
  65. // 构建当前行数据
  66. $build[$key] = $sheet->getCellByColumnAndRow($col, $row)->getValue();
  67. }
  68. $data[] = $build; //当前行数据
  69. }
  70. return $data;
  71. }
  72. }