ImportService.php 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. <?php
  2. namespace App\Service;
  3. use App\Exports\TableHeadExport;
  4. use App\Import\Import;
  5. use App\Import\ImportAll;
  6. use App\Model\BasicType;
  7. use App\Model\Customer;
  8. use App\Model\CustomerInfo;
  9. use App\Model\Depart;
  10. use App\Model\Employee;
  11. use App\Model\Product;
  12. use App\Model\ProductCategory;
  13. use App\Model\ProductPriceDetail;
  14. use App\Model\SalesOrder;
  15. use App\Model\SalesOrderInfo;
  16. use App\Model\SalesOrderProductInfo;
  17. use Illuminate\Support\Facades\DB;
  18. use Illuminate\Support\Facades\Log;
  19. use Illuminate\Support\Facades\Storage;
  20. use Maatwebsite\Excel\Facades\Excel;
  21. use PhpOffice\PhpSpreadsheet\IOFactory;
  22. class ImportService extends Service
  23. {
  24. const tmp_dir = 'upload_occ';
  25. const string = '/api/getFile/';
  26. const file_one = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
  27. const file_two = 'application/zip';
  28. const file_array = [
  29. self::file_one,
  30. self::file_two,
  31. ];
  32. //文件类型
  33. const FILE_TYPE = [
  34. 'txt',
  35. 'jpg',
  36. 'png',
  37. 'gif',
  38. 'jpeg',
  39. 'zip',
  40. 'rar',
  41. 'xlsx',
  42. 'xls'
  43. ];
  44. //导入入口
  45. public function import($data){
  46. // //不超时
  47. // ini_set('max_execution_time', 0);
  48. // //内存设置
  49. // ini_set('memory_limit', -1);
  50. // $reader = IOFactory::createReader('Xlsx');
  51. // $reader->setReadDataOnly(true); // 只读取有数据的单元格
  52. // $spreadsheet = $reader->load($data['file']);
  53. // dd($spreadsheet);
  54. // // 创建一个Reader对象
  55. // $reader = IOFactory::createReader('Xlsx'); // 根据你的文件格式选择合适的reader
  56. //
  57. //// 加载Excel文件
  58. // $spreadsheet = $reader->load($data['file']);
  59. //
  60. //// 获取第一个工作表
  61. // $worksheet = $spreadsheet->getActiveSheet();
  62. //
  63. //// 获取总行数
  64. // $totalRows = $worksheet->getHighestRow();dd($totalRows);
  65. if(empty($data['file'])) return [false,'导入文件不能为空'];
  66. try {
  67. $this->uploadFile($data['file']);
  68. }catch (\Throwable $exception) {
  69. return [false, $exception->getMessage() . ' (Code: ' . $exception->getCode() . ', Line: ' . $exception->getLine() . ')'];
  70. }
  71. return [true, ''];
  72. }
  73. public function uploadFile($file){
  74. if(empty($file)) return [false, '请上传文件'];
  75. // 获取文件相关信息
  76. $ext = $file->getClientOriginalExtension(); // 扩展名
  77. $realPath = $file->getRealPath(); //临时文件的绝对路径
  78. $ext = strtolower($ext);
  79. if (! in_array($ext, self::FILE_TYPE)){
  80. $str = '文件格式为:';
  81. foreach (self::FILE_TYPE as $value){
  82. $str.= $value . ' ' ;
  83. }
  84. return [false, $str];
  85. }
  86. $date = date("Y-m-d");
  87. //文件名
  88. $file_name = date("Ymd").time().rand(1000,9999);
  89. $filename = $file_name.'.' . $ext;
  90. $dir = self::tmp_dir . '/' . $date . '/' . $filename;
  91. Storage::disk('public')->put($dir, file_get_contents($realPath));
  92. return [true, self::string . $filename];
  93. }
  94. public function getFileData($data){
  95. if(empty($data['url'])) return [false, '文件路径不能为空'];
  96. try {
  97. // 发送 HTTP 请求获取文件内容
  98. $response = file_get_contents($data['url']);
  99. } catch (\Throwable $exception) {
  100. if (str_contains($exception->getMessage(), 'failed to open stream')) return [false, "URL链接已失效"];
  101. return [false, $exception->getMessage()];
  102. }
  103. if ($response === false) return [false, '文件获取失败'];
  104. // 创建一个临时文件资源
  105. $tempFile = tempnam(sys_get_temp_dir(), 'download_');
  106. file_put_contents($tempFile, $response);
  107. // 判断文件类型
  108. $fileInfo = finfo_open(FILEINFO_MIME_TYPE);
  109. $mimeType = finfo_file($fileInfo, $tempFile);
  110. finfo_close($fileInfo);
  111. if(! in_array($mimeType, self::file_array)) return [false, '文件类型目前暂时支持zip|xlsx'];
  112. // 根据文件类型处理
  113. if ($mimeType === self::file_one) {
  114. // 处理单个XLSX文件
  115. list($status,$result) = $this->processXlsxFile($tempFile);
  116. if (! $status) return [false, $result];
  117. return [true, ['xlsx' => $result]];
  118. } elseif ($mimeType === self::file_two) {
  119. // 创建 ZipArchive 对象
  120. $zip = new \ZipArchive();
  121. if ($zip->open($tempFile) !== true) {
  122. // 删除临时文件
  123. unlink($tempFile);
  124. return [false, '无法打开ZIP文件'];
  125. }
  126. // 初始化一个数组来存储所有XLSX文件的数据
  127. $allFilesData = [];
  128. // 遍历ZIP文件中的每一个文件
  129. for ($i = 0; $i < $zip->numFiles; $i++) {
  130. $filename = $zip->getNameIndex($i);
  131. if (pathinfo($filename, PATHINFO_EXTENSION) === 'xlsx') {// 检查是否为XLSX文件
  132. // 提取文件到临时位置
  133. $tempXlsxFile = tempnam(sys_get_temp_dir(), 'xlsx_');
  134. // 提取文件到临时位置
  135. if ($zip->extractTo(sys_get_temp_dir(), [$filename]) === false) {
  136. continue; // 跳过提取失败的文件
  137. }
  138. // 获取提取出的文件的实际路径
  139. $extractedFile = sys_get_temp_dir() . '/' . basename($filename);
  140. // 检查临时文件是否存在
  141. if (! file_exists($extractedFile)) continue;
  142. // 重命名提取出的文件为临时文件
  143. if (!rename($extractedFile, $tempXlsxFile)) {
  144. continue;
  145. }
  146. list($status,$xlsxData) = $this->processXlsxFile($tempXlsxFile);
  147. if (! $status) return [false, $xlsxData];
  148. // 将当前XLSX文件的数据添加到所有文件的数据数组中
  149. $xlsxData['filename'] = $filename;
  150. $allFilesData[] = $xlsxData;
  151. }
  152. }
  153. // 关闭 ZIP 文件
  154. $zip->close();
  155. // 删除临时 ZIP 文件
  156. unlink($tempFile);
  157. return [true, ["zip" => $allFilesData]];
  158. } else {
  159. // 删除临时文件
  160. unlink($tempFile);
  161. return [false, '不支持的文件类型'];
  162. }
  163. }
  164. // 定义一个函数来处理XLSX文件
  165. function processXlsxFile($filename) {
  166. try {
  167. if (is_file($filename)) {
  168. chmod($filename, 0777);
  169. }
  170. // 使用 PhpSpreadsheet 读取文件
  171. $reader = IOFactory::createReader('Xlsx');
  172. $spreadsheet = $reader->load($filename);
  173. // 初始化一个数组来存储所有工作表的数据
  174. $allSheetData = [];
  175. // 遍历所有工作表
  176. foreach ($spreadsheet->getWorksheetIterator() as $worksheet) {
  177. $sheetData = [];
  178. foreach ($worksheet->getRowIterator() as $row) {
  179. $cellIterator = $row->getCellIterator();
  180. $cellIterator->setIterateOnlyExistingCells(false); // 循环所有单元格,即使它未设置
  181. $rowData = [];
  182. foreach ($cellIterator as $cell) {
  183. $rowData[] = $cell->getValue();
  184. }
  185. $sheetData[] = $rowData;
  186. }
  187. // 将当前工作表的数据添加到总数据数组中
  188. $allSheetData[$worksheet->getTitle()] = $sheetData;
  189. }
  190. // 删除临时文件
  191. unlink($filename);
  192. return [true, $allSheetData];
  193. } catch (\Throwable $e) {
  194. // 删除临时文件
  195. unlink($filename);
  196. return [false, "处理文件 {$filename} 时发生错误: " . $e->getMessage()];
  197. }
  198. }
  199. public function getFileData1($data){
  200. if(empty($data['url'])) return [false, '文件路径不能为空'];
  201. try{
  202. // 发送 HTTP 请求获取文件内容
  203. $response = file_get_contents($data['url']);
  204. }catch (\Throwable $exception){
  205. return [false, $exception->getMessage()];
  206. }
  207. if ($response === false) return [false, '文件获取失败'];
  208. // 创建一个临时文件资源
  209. $tempFile = tempnam(sys_get_temp_dir(), 'xlsx_');
  210. file_put_contents($tempFile, $response);
  211. // 使用 phpspreadsheet 读取文件
  212. try {
  213. // 创建一个 Xlsx 读取器
  214. $reader = IOFactory::createReader('Xlsx');
  215. // 加载临时文件
  216. $spreadsheet = $reader->load($tempFile);
  217. // 初始化一个数组来存储所有工作表的数据
  218. $allSheetData = [];
  219. // 遍历所有工作表
  220. foreach ($spreadsheet->getWorksheetIterator() as $worksheet) {
  221. $sheetData = [];
  222. foreach ($worksheet->getRowIterator() as $row) {
  223. $cellIterator = $row->getCellIterator();
  224. $cellIterator->setIterateOnlyExistingCells(false); // Loop all cells, even if it is not set
  225. $rowData = [];
  226. foreach ($cellIterator as $cell) {
  227. $rowData[] = $cell->getValue();
  228. }
  229. $sheetData[] = $rowData;
  230. }
  231. // 将当前工作表的数据添加到总数据数组中
  232. $allSheetData[$worksheet->getTitle()] = $sheetData;
  233. }
  234. // 删除临时文件
  235. unlink($tempFile);
  236. } catch (\Exception $e) {
  237. // 删除临时文件
  238. unlink($tempFile);
  239. return [false, $e->getMessage()];
  240. }
  241. return [true , $allSheetData];
  242. }
  243. }