ImportService.php 14 KB

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