ImportService.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  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, ['content' => [$result], 'type' => 'xlsx']];
  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. $tempDir = sys_get_temp_dir() . '/extracted_' . uniqid();
  135. mkdir($tempDir, 0777, true);
  136. // 提取文件到临时位置
  137. if ($zip->extractTo($tempDir, [$filename]) === false) {
  138. $this->deleteDirectory($tempDir);
  139. // Log::channel('apiLog')->info('断点1', ["message" => $filename]);
  140. continue; // 跳过提取失败的文件
  141. }
  142. // 递归查找提取的XLSX文件
  143. $extractedFile = $this->findXlsxFile($tempDir, basename($filename));
  144. // 获取提取出的文件的实际路径
  145. // $extractedFile = sys_get_temp_dir() . '/' . basename($filename);
  146. // 检查临时文件是否存在
  147. if (! file_exists($extractedFile)){
  148. $this->deleteDirectory($tempDir);
  149. // Log::channel('apiLog')->info('断点2', ["message" => $extractedFile]);
  150. continue;
  151. }
  152. // 重命名提取出的文件为临时文件
  153. $tempXlsxFile = tempnam(sys_get_temp_dir(), 'xlsx_');
  154. if (! rename($extractedFile, $tempXlsxFile)) {
  155. $this->deleteDirectory($tempDir);
  156. // Log::channel('apiLog')->info('断点5', ["message" => "重命名文件失败: " . $extractedFile]);
  157. continue;
  158. }
  159. // // 重命名提取出的文件为临时文件
  160. // if (! rename($extractedFile, $tempXlsxFile)) {
  161. // Log::channel('apiLog')->info('断点3', ["message" => $tempXlsxFile]);
  162. // continue;
  163. // }
  164. list($status,$xlsxData) = $this->processXlsxFile($tempXlsxFile);
  165. if (! $status) {
  166. $this->deleteDirectory($tempDir);
  167. return [false, $xlsxData];
  168. }
  169. // 将当前XLSX文件的数据添加到所有文件的数据数组中
  170. $xlsxData['filename'] = $filename;
  171. $allFilesData[] = $xlsxData;
  172. $this->deleteDirectory($tempDir);
  173. }
  174. }
  175. // 关闭 ZIP 文件
  176. $zip->close();
  177. // 删除临时 ZIP 文件
  178. unlink($tempFile);
  179. return [true, ["content" => $allFilesData, 'type' => 'zip']];
  180. } else {
  181. // 删除临时文件
  182. unlink($tempFile);
  183. return [false, '不支持的文件类型'];
  184. }
  185. }
  186. // 递归删除目录及其所有内容
  187. function deleteDirectory($dir) {
  188. if (! is_dir($dir)) {
  189. return;
  190. }
  191. $files = array_diff(scandir($dir), array('.', '..'));
  192. foreach ($files as $file) {
  193. $path = $dir . DIRECTORY_SEPARATOR . $file;
  194. if (is_dir($path)) {
  195. $this->deleteDirectory($path);
  196. } else {
  197. unlink($path);
  198. }
  199. }
  200. rmdir($dir);
  201. }
  202. // 递归查找XLSX文件
  203. function findXlsxFile($dir, $filename) {
  204. $iterator = new \RecursiveDirectoryIterator($dir);
  205. $files = new \RecursiveIteratorIterator($iterator, \RecursiveIteratorIterator::SELF_FIRST);
  206. foreach ($files as $file) {
  207. if ($file->isFile() && $file->getFilename() === $filename) {
  208. return $file->getPathname();
  209. }
  210. }
  211. return null;
  212. }
  213. // 定义一个函数来处理XLSX文件
  214. function processXlsxFile($filename) {
  215. try {
  216. if (is_file($filename)) {
  217. chmod($filename, 0777);
  218. }
  219. // 使用 PhpSpreadsheet 读取文件
  220. $reader = IOFactory::createReader('Xlsx');
  221. $spreadsheet = $reader->load($filename);
  222. // 初始化一个数组来存储所有工作表的数据
  223. $allSheetData = [];
  224. // 遍历所有工作表
  225. foreach ($spreadsheet->getWorksheetIterator() as $worksheet) {
  226. $sheetData = [];
  227. foreach ($worksheet->getRowIterator() as $row) {
  228. $cellIterator = $row->getCellIterator();
  229. $cellIterator->setIterateOnlyExistingCells(false); // 循环所有单元格,即使它未设置
  230. $rowData = [];
  231. foreach ($cellIterator as $cell) {
  232. $rowData[] = $cell->getFormattedValue();
  233. }
  234. $sheetData[] = $rowData;
  235. }
  236. // 将当前工作表的数据添加到总数据数组中
  237. $allSheetData[$worksheet->getTitle()] = $sheetData;
  238. }
  239. // 删除临时文件
  240. unlink($filename);
  241. return [true, $allSheetData];
  242. } catch (\Throwable $e) {
  243. // 删除临时文件
  244. unlink($filename);
  245. return [false, "处理文件 {$filename} 时发生错误: " . $e->getMessage()];
  246. }
  247. }
  248. public function getFileData1($data){
  249. if(empty($data['url'])) return [false, '文件路径不能为空'];
  250. try{
  251. // 发送 HTTP 请求获取文件内容
  252. $response = file_get_contents($data['url']);
  253. }catch (\Throwable $exception){
  254. return [false, $exception->getMessage()];
  255. }
  256. if ($response === false) return [false, '文件获取失败'];
  257. // 创建一个临时文件资源
  258. $tempFile = tempnam(sys_get_temp_dir(), 'xlsx_');
  259. file_put_contents($tempFile, $response);
  260. // 使用 phpspreadsheet 读取文件
  261. try {
  262. // 创建一个 Xlsx 读取器
  263. $reader = IOFactory::createReader('Xlsx');
  264. // 加载临时文件
  265. $spreadsheet = $reader->load($tempFile);
  266. // 初始化一个数组来存储所有工作表的数据
  267. $allSheetData = [];
  268. // 遍历所有工作表
  269. foreach ($spreadsheet->getWorksheetIterator() as $worksheet) {
  270. $sheetData = [];
  271. foreach ($worksheet->getRowIterator() as $row) {
  272. $cellIterator = $row->getCellIterator();
  273. $cellIterator->setIterateOnlyExistingCells(false); // Loop all cells, even if it is not set
  274. $rowData = [];
  275. foreach ($cellIterator as $cell) {
  276. $rowData[] = $cell->getValue();
  277. }
  278. $sheetData[] = $rowData;
  279. }
  280. // 将当前工作表的数据添加到总数据数组中
  281. $allSheetData[$worksheet->getTitle()] = $sheetData;
  282. }
  283. // 删除临时文件
  284. unlink($tempFile);
  285. } catch (\Exception $e) {
  286. // 删除临时文件
  287. unlink($tempFile);
  288. return [false, $e->getMessage()];
  289. }
  290. return [true , $allSheetData];
  291. }
  292. }