Import.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. <?php namespace Excel\Lib;
  2. use Dever;
  3. Dever::apply('autoload', 'excel', 'vendor');
  4. class Import extends Core
  5. {
  6. public function act($file = '', $sheet = 0, $offset = 0)
  7. {
  8. $file = mb_convert_encoding($file, "UTF-8", "gbk");
  9. if(empty($file) OR !file_exists($file)) {
  10. Dever::error('file not exists!');
  11. }
  12. try {
  13. $type = \PhpOffice\PhpSpreadsheet\IOFactory::identify($file);
  14. $read = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($type);
  15. //$read->setReadDataOnly(true);
  16. $excel = $read->load($file);
  17. } catch (\Exception $e) {
  18. Dever::error('加载文件发生错误:"'.$file.'": '. $e->getMessage());
  19. }
  20. $sheet = $excel->getSheet($sheet);
  21. $columnH = $sheet->getHighestColumn();
  22. $columnCnt = array_search($columnH, $this->cell);
  23. if (!$columnCnt) {
  24. $columnCnt = $offset - 1;
  25. }
  26. if ($columnCnt < 0) {
  27. $columnCnt = 0;
  28. }
  29. $rowCnt = $sheet->getHighestRow();
  30. $data = array();
  31. for ($_row = 1; $_row <= $rowCnt; $_row++) {
  32. for ($_column = 0; $_column <= $columnCnt; $_column++) {
  33. $cellId = $this->cell[$_column].$_row;
  34. //$cellValue = $sheet->getCell($cellId)->getValue();
  35. $cellValue = $sheet->getCell($cellId)->getCalculatedValue();
  36. if ($cellValue instanceof \PhpOffice\PhpSpreadsheet\RichText\RichText) {
  37. $cellValue = $cellValue->__toString();
  38. }
  39. $data[$_row][$this->cell[$_column]] = $cellValue;
  40. }
  41. }
  42. $draws = $sheet->getDrawingCollection();
  43. //处理图片
  44. foreach ($draws as $img) {
  45. list($startColumn, $startRow) = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::coordinateFromString($img->getCoordinates());//获取图片所在行和列
  46. $pic = Dever::load('save', 'upload')->act(1, $img->getPath());
  47. //插入代码
  48. //$startColumn = $this->decimal($startColumn);//由于图片所在位置的列号为字母,转化为数字
  49. $data[$startRow][$startColumn] = $pic['url'];
  50. }
  51. return $data;
  52. }
  53. }