ImportExcel.php 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. <?php
  2. namespace App\Admin\Actions\Post;
  3. use App\Model\TextLabel;
  4. use Encore\Admin\Actions\Action;
  5. use Illuminate\Http\Request;
  6. use Illuminate\Support\Facades\Storage;
  7. use PHPExcel_IOFactory;
  8. class ImportExcel extends Action
  9. {
  10. protected $selector = '.import-excel';
  11. public function handle(Request $request)
  12. {
  13. $oFile = $request->file('file');
  14. Storage::disk('local')->put('text.xlsx',file_get_contents($oFile));
  15. $url = storage_path().'/app/text.xlsx';
  16. $excel = PHPExcel_IOFactory::load($url);
  17. $sheet = $excel->getSheet(0);
  18. $row_num = $sheet->getHighestRow();
  19. $data = [];
  20. for ($row = 2;$row <= $row_num;$row++){
  21. $text = $excel->getActiveSheet()->getCell("A".$row)->getValue();
  22. $length = mb_strlen($text);
  23. if ($length <= 510){
  24. $data[]['text'] = $text;
  25. }elseif ($length > 510 && $length <= 1020){
  26. $textArray = preg_split('/。/',$text);
  27. $count = count($textArray);
  28. $pos = ceil($count / 2);
  29. $text1 = '';
  30. $text2 = '';
  31. foreach ($textArray as $key => $item){
  32. if ($key <= $pos){
  33. $text1 .= $item.'。';
  34. }else{
  35. $text2 .= $item.'。';
  36. }
  37. }
  38. $data[]['text'] = $text1;
  39. $data[]['text'] = $text2;
  40. }elseif ($length > 1020){
  41. $textArray = preg_split('/。/',$text);
  42. $count = count($textArray);
  43. $pos = ceil($count / 3);
  44. $text1 = '';
  45. $text2 = '';
  46. $text3 = '';
  47. foreach ($textArray as $key => $item){
  48. if ($key <= $pos){
  49. $text1 .= $item;
  50. }elseif($key <= $pos*2){
  51. $text2 .= $item.'。';
  52. }else{
  53. $text3 .= $item.'。';
  54. }
  55. }
  56. $data[]['text'] = $text1;
  57. $data[]['text'] = $text2;
  58. $data[]['text'] = $text3;
  59. }
  60. }
  61. TextLabel::query()->insert($data);
  62. return $this->response()->success('Success message...')->refresh();
  63. }
  64. public function form()
  65. {
  66. $this->file('file', '请选择文件');
  67. }
  68. public function html()
  69. {
  70. return <<<HTML
  71. <a class="btn btn-sm btn-default import-excel">导入EXCEL</a>
  72. HTML;
  73. }
  74. }