ImportService.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  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. use PhpOffice\PhpSpreadsheet\Shared\Date;
  23. class ImportService extends Service
  24. {
  25. const tmp_dir = 'upload_occ';
  26. const string = '/api/getFile/';
  27. const file_one = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
  28. const file_two = 'application/zip';
  29. const file_three = 'application/octet-stream';
  30. const file_array = [
  31. self::file_one,
  32. self::file_two,
  33. self::file_three,
  34. ];
  35. //文件类型
  36. const FILE_TYPE = [
  37. 'txt',
  38. 'jpg',
  39. 'png',
  40. 'gif',
  41. 'jpeg',
  42. 'zip',
  43. 'rar',
  44. 'xlsx',
  45. 'xls'
  46. ];
  47. //导入入口
  48. public function import($data){
  49. // //不超时
  50. // ini_set('max_execution_time', 0);
  51. // //内存设置
  52. // ini_set('memory_limit', -1);
  53. // $reader = IOFactory::createReader('Xlsx');
  54. // $reader->setReadDataOnly(true); // 只读取有数据的单元格
  55. // $spreadsheet = $reader->load($data['file']);
  56. // dd($spreadsheet);
  57. // // 创建一个Reader对象
  58. // $reader = IOFactory::createReader('Xlsx'); // 根据你的文件格式选择合适的reader
  59. //
  60. //// 加载Excel文件
  61. // $spreadsheet = $reader->load($data['file']);
  62. //
  63. //// 获取第一个工作表
  64. // $worksheet = $spreadsheet->getActiveSheet();
  65. //
  66. //// 获取总行数
  67. // $totalRows = $worksheet->getHighestRow();dd($totalRows);
  68. if(empty($data['file'])) return [false,'导入文件不能为空'];
  69. try {
  70. $this->uploadFile($data['file']);
  71. }catch (\Throwable $exception) {
  72. return [false, $exception->getMessage() . ' (Code: ' . $exception->getCode() . ', Line: ' . $exception->getLine() . ')'];
  73. }
  74. return [true, ''];
  75. }
  76. public function uploadFile($file){
  77. if(empty($file)) return [false, '请上传文件'];
  78. // 获取文件相关信息
  79. $ext = $file->getClientOriginalExtension(); // 扩展名
  80. $realPath = $file->getRealPath(); //临时文件的绝对路径
  81. $ext = strtolower($ext);
  82. if (! in_array($ext, self::FILE_TYPE)){
  83. $str = '文件格式为:';
  84. foreach (self::FILE_TYPE as $value){
  85. $str.= $value . ' ' ;
  86. }
  87. return [false, $str];
  88. }
  89. $date = date("Y-m-d");
  90. //文件名
  91. $file_name = date("Ymd").time().rand(1000,9999);
  92. $filename = $file_name.'.' . $ext;
  93. $dir = self::tmp_dir . '/' . $date . '/' . $filename;
  94. Storage::disk('public')->put($dir, file_get_contents($realPath));
  95. return [true, self::string . $filename];
  96. }
  97. public function getFileData($data){
  98. if(empty($data['url'])) return [false, '文件路径不能为空'];
  99. try {
  100. // 发送 HTTP 请求获取文件内容
  101. $response = file_get_contents($data['url']);
  102. } catch (\Throwable $exception) {
  103. if (str_contains($exception->getMessage(), 'failed to open stream')) return [false, "URL链接已失效"];
  104. return [false, $exception->getMessage()];
  105. }
  106. if ($response === false) return [false, '文件获取失败'];
  107. // 创建一个临时文件资源
  108. $tempFile = tempnam(sys_get_temp_dir(), 'download_');
  109. file_put_contents($tempFile, $response);
  110. // 判断文件类型
  111. $fileInfo = finfo_open(FILEINFO_MIME_TYPE);
  112. $mimeType = finfo_file($fileInfo, $tempFile);
  113. finfo_close($fileInfo);
  114. if(! in_array($mimeType, self::file_array)) return [false, '文件类型目前暂时支持zip|xlsx'];
  115. // 根据文件类型处理
  116. if ($mimeType === self::file_one) {
  117. // 处理单个XLSX文件
  118. list($status,$result) = $this->processXlsxFile($tempFile);
  119. if (! $status) return [false, $result];
  120. return [true, ['content' => [$result], 'type' => 'xlsx']];
  121. } elseif ($mimeType === self::file_two) {
  122. // 创建 ZipArchive 对象
  123. $zip = new \ZipArchive();
  124. if ($zip->open($tempFile) !== true) {
  125. // 删除临时文件
  126. unlink($tempFile);
  127. return [false, '无法打开ZIP文件'];
  128. }
  129. // 初始化一个数组来存储所有XLSX文件的数据
  130. $allFilesData = [];
  131. // 遍历ZIP文件中的每一个文件
  132. for ($i = 0; $i < $zip->numFiles; $i++) {
  133. $filename = $zip->getNameIndex($i);
  134. if (pathinfo($filename, PATHINFO_EXTENSION) === 'xlsx') {// 检查是否为XLSX文件
  135. // 提取文件到临时位置
  136. // $tempXlsxFile = tempnam(sys_get_temp_dir(), 'xlsx_');
  137. $tempDir = sys_get_temp_dir() . '/extracted_' . uniqid();
  138. mkdir($tempDir, 0777, true);
  139. // 提取文件到临时位置
  140. if ($zip->extractTo($tempDir, [$filename]) === false) {
  141. $this->deleteDirectory($tempDir);
  142. // Log::channel('apiLog')->info('断点1', ["message" => $filename]);
  143. continue; // 跳过提取失败的文件
  144. }
  145. // 递归查找提取的XLSX文件
  146. $extractedFile = $this->findXlsxFile($tempDir, basename($filename));
  147. // 获取提取出的文件的实际路径
  148. // $extractedFile = sys_get_temp_dir() . '/' . basename($filename);
  149. // 检查临时文件是否存在
  150. if (! file_exists($extractedFile)){
  151. $this->deleteDirectory($tempDir);
  152. // Log::channel('apiLog')->info('断点2', ["message" => $extractedFile]);
  153. continue;
  154. }
  155. // 重命名提取出的文件为临时文件
  156. $tempXlsxFile = tempnam(sys_get_temp_dir(), 'xlsx_');
  157. if (! rename($extractedFile, $tempXlsxFile)) {
  158. $this->deleteDirectory($tempDir);
  159. // Log::channel('apiLog')->info('断点5', ["message" => "重命名文件失败: " . $extractedFile]);
  160. continue;
  161. }
  162. // // 重命名提取出的文件为临时文件
  163. // if (! rename($extractedFile, $tempXlsxFile)) {
  164. // Log::channel('apiLog')->info('断点3', ["message" => $tempXlsxFile]);
  165. // continue;
  166. // }
  167. list($status,$xlsxData) = $this->processXlsxFile($tempXlsxFile);
  168. if (! $status) {
  169. $this->deleteDirectory($tempDir);
  170. return [false, $xlsxData];
  171. }
  172. // 将当前XLSX文件的数据添加到所有文件的数据数组中
  173. $xlsxData['filename'] = $filename;
  174. $allFilesData[] = $xlsxData;
  175. $this->deleteDirectory($tempDir);
  176. }
  177. }
  178. // 关闭 ZIP 文件
  179. $zip->close();
  180. // 删除临时 ZIP 文件
  181. unlink($tempFile);
  182. return [true, ["content" => $allFilesData, 'type' => 'zip']];
  183. } elseif ($mimeType === self::file_three){
  184. // 处理单个XLSX文件
  185. list($status,$result) = $this->processXlsxFile($tempFile);
  186. if (! $status) return [false, $result];
  187. return [true, ['content' => [$result], 'type' => 'xlsx']];
  188. }else {
  189. // 删除临时文件
  190. unlink($tempFile);
  191. return [false, '不支持的文件类型'];
  192. }
  193. }
  194. // 递归删除目录及其所有内容
  195. function deleteDirectory($dir) {
  196. if (! is_dir($dir)) {
  197. return;
  198. }
  199. $files = array_diff(scandir($dir), array('.', '..'));
  200. foreach ($files as $file) {
  201. $path = $dir . DIRECTORY_SEPARATOR . $file;
  202. if (is_dir($path)) {
  203. $this->deleteDirectory($path);
  204. } else {
  205. unlink($path);
  206. }
  207. }
  208. rmdir($dir);
  209. }
  210. // 递归查找XLSX文件
  211. function findXlsxFile($dir, $filename) {
  212. $iterator = new \RecursiveDirectoryIterator($dir);
  213. $files = new \RecursiveIteratorIterator($iterator, \RecursiveIteratorIterator::SELF_FIRST);
  214. foreach ($files as $file) {
  215. if ($file->isFile() && $file->getFilename() === $filename) {
  216. return $file->getPathname();
  217. }
  218. }
  219. return null;
  220. }
  221. // 定义一个函数来处理XLSX文件
  222. function processXlsxFile($filename) {
  223. try {
  224. if (is_file($filename)) {
  225. chmod($filename, 0777);
  226. }
  227. // 使用 PhpSpreadsheet 读取文件
  228. $reader = IOFactory::createReader('Xlsx');
  229. $spreadsheet = $reader->load($filename);
  230. // 初始化一个数组来存储所有工作表的数据
  231. $allSheetData = [];
  232. // 遍历所有工作表
  233. foreach ($spreadsheet->getWorksheetIterator() as $worksheet) {
  234. $sheetData = [];
  235. foreach ($worksheet->getRowIterator() as $row) {
  236. $cellIterator = $row->getCellIterator();
  237. $cellIterator->setIterateOnlyExistingCells(false); // 循环所有单元格,即使它未设置
  238. $rowData = [];
  239. foreach ($cellIterator as $cell) {
  240. // 判断单元格是否为日期
  241. if (Date::isDateTime($cell)) {
  242. // 将日期转换为 Y-m-d 格式
  243. $formattedDate = Date::excelToDateTimeObject($cell->getValue())->format('Y-m-d');
  244. $rowData[] = $formattedDate;
  245. } else {
  246. // 获取单元格的格式化值
  247. $rowData[] = trim($cell->getFormattedValue());
  248. }
  249. // $cellData = $cell->getFormattedValue();
  250. // if(! empty($cellData)) $cellData = $this->convertToYMD($cellData);
  251. // $rowData[] = $cellData;
  252. }
  253. $sheetData[] = $rowData;
  254. }
  255. // 将当前工作表的数据添加到总数据数组中
  256. $allSheetData[$worksheet->getTitle()] = $sheetData;
  257. }
  258. // 删除临时文件
  259. unlink($filename);
  260. return [true, $allSheetData];
  261. } catch (\Throwable $e) {
  262. // 删除临时文件
  263. unlink($filename);
  264. return [false, "处理文件 {$filename} 时发生错误: " . $e->getMessage()];
  265. }
  266. }
  267. public function convertToYMD($date)
  268. {
  269. // 定义一些常见的日期格式
  270. $formats = [
  271. 'Y-m-d', // 2023-10-17
  272. 'Y/m/d', // 2023/10/17
  273. 'd-m-Y', // 17-10-2023
  274. 'd/m/Y', // 17/10/2023
  275. 'm-d-Y', // 10-17-2023
  276. 'm/d/Y', // 10/17/2023
  277. // 'Ymd', // 20231017
  278. // 'dmy', // 17102023
  279. // 'dmY', // 17102023
  280. // 'dMY', // 17102023
  281. // 'Ymd', // 20231017
  282. // 'Ydm', // 20231017
  283. // 'YDM', // 20231017
  284. // 'YDm', // 20231017
  285. ];
  286. // 尝试使用每个格式解析日期
  287. foreach ($formats as $format) {
  288. $dateTime = \DateTime::createFromFormat($format, $date);
  289. if ($dateTime && $dateTime->format($format) === $date) {
  290. // 成功解析日期,返回转换后的 Y-m-d 格式
  291. return $dateTime->format('Y-m-d');
  292. }
  293. }
  294. // 如果所有格式都未能解析日期,则返回原字符串
  295. return $date;
  296. }
  297. public function getFileData1($data){
  298. if(empty($data['url'])) return [false, '文件路径不能为空'];
  299. try{
  300. // 发送 HTTP 请求获取文件内容
  301. $response = file_get_contents($data['url']);
  302. }catch (\Throwable $exception){
  303. return [false, $exception->getMessage()];
  304. }
  305. if ($response === false) return [false, '文件获取失败'];
  306. // 创建一个临时文件资源
  307. $tempFile = tempnam(sys_get_temp_dir(), 'xlsx_');
  308. file_put_contents($tempFile, $response);
  309. // 使用 phpspreadsheet 读取文件
  310. try {
  311. // 创建一个 Xlsx 读取器
  312. $reader = IOFactory::createReader('Xlsx');
  313. // 加载临时文件
  314. $spreadsheet = $reader->load($tempFile);
  315. // 初始化一个数组来存储所有工作表的数据
  316. $allSheetData = [];
  317. // 遍历所有工作表
  318. foreach ($spreadsheet->getWorksheetIterator() as $worksheet) {
  319. $sheetData = [];
  320. foreach ($worksheet->getRowIterator() as $row) {
  321. $cellIterator = $row->getCellIterator();
  322. $cellIterator->setIterateOnlyExistingCells(false); // Loop all cells, even if it is not set
  323. $rowData = [];
  324. foreach ($cellIterator as $cell) {
  325. $rowData[] = $cell->getValue();
  326. }
  327. $sheetData[] = $rowData;
  328. }
  329. // 将当前工作表的数据添加到总数据数组中
  330. $allSheetData[$worksheet->getTitle()] = $sheetData;
  331. }
  332. // 删除临时文件
  333. unlink($tempFile);
  334. } catch (\Exception $e) {
  335. // 删除临时文件
  336. unlink($tempFile);
  337. return [false, $e->getMessage()];
  338. }
  339. return [true , $allSheetData];
  340. }
  341. }