diff --git a/application/admin/controller/Order.php b/application/admin/controller/Order.php index e2fcc4c..b2f51a8 100644 --- a/application/admin/controller/Order.php +++ b/application/admin/controller/Order.php @@ -1100,7 +1100,7 @@ class Order extends Backend } - public function export() + /*public function export() { // 表头结构(可从参数获取或手动定义) $columns = json_decode($this->request->get('columns', ''), true); @@ -1140,6 +1140,94 @@ class Order extends Backend }; $this->exportCsvByStream($columns, $fetchData, '订单导出_' . date('Ymd_His') . '.xlsx'); + }*/ + + public function export() + { + $columns = json_decode($this->request->get('columns', ''), true); + if (!$columns) { + $sample = $this->index(true, 1, 1)->getData(); + if (!isset($sample['rows'][0])) { + return json(['code' => 0, 'msg' => '无数据可导出']); + } + $columns = []; + foreach ($sample['rows'][0] as $key => $value) { + $columns[] = ['field' => $key, 'title' => $key]; + } + } + + $generator = function () use ($columns) { + $limit = 1000; + $page = 1; + $order = new \app\admin\model\Order(); + + do { + $result = $this->index(true, $page, $limit); + $rows = $result->getData()['rows'] ?? []; + if (!$rows) break; + + foreach ($rows as $item) { + $item->status = $order->getStatusList()[$item->status] ?? ''; + $item->dispatch_type = $item->dispatch_type == 1 ? '手动派单' : '自动派单'; + $item->is_overtime = $item->is_overtime ? '超时' : '未超时'; + $item->receive_type = $item->receive_type == 1 ? '已收定金' : '已收全款'; + + $images = explode(',', $item->images ?? ''); + $url = ''; + foreach ($images as $img) { + if ($img === '') continue; + $url .= cdnurl($img) . ','; + } + $item->images = $url; + + yield $item->toArray(); + } + + $page++; + } while (count($rows) === $limit); + }; + + $this->streamCsv($columns, $generator(), '订单导出_' . date('Ymd_His') . '.csv'); + } + + + protected function streamCsv(array $columns, \Generator $rows, string $filename) + { + set_time_limit(0); + ini_set('memory_limit', '-1'); + ignore_user_abort(true); + + header('Content-Type: text/csv; charset=UTF-8'); + header('Content-Disposition: attachment;filename="' . $filename . '"'); + header('Cache-Control: max-age=0'); + header('Pragma: public'); + + // 防止 Excel 打开乱码 + echo "\xEF\xBB\xBF"; + + $output = fopen('php://output', 'w'); + + $fields = array_column($columns, 'field'); + $titles = array_column($columns, 'title'); + + // 写入表头 + fputcsv($output, $titles); + + // 逐行写入数据 + foreach ($rows as $row) { + $line = []; + foreach ($fields as $field) { + $value = $this->getNestedValue($row, $field); + if (is_array($value) || is_object($value)) { + $value = json_encode($value, JSON_UNESCAPED_UNICODE); + } + $line[] = $value; + } + fputcsv($output, $line); + } + + fclose($output); + exit; }