메모리에 있는 data 를 excel file 로 download 하기
아래처럼 하면 data 를 excel로 download 할 수 있다.response()->stream 을 지원하지 않아서 ref. 3을 참고해서 stream response 를 만들었다.
<?php use App\Http\Controllers\Controller; use Illuminate\Http\Request; use Symfony\Component\HttpFoundation\StreamedResponse; class ExcelController extends Controller { public function excelDeductPreInvest(Request $request){ $recs = ['test', 'test'] $filename = 'test.xlsx'; $headers = [ 'Cache-Control' => 'must-revalidate, post-check=0, pre-check=0' ,'Content-type' => 'application/vnd.ms-excel' ,'Content-Disposition' => "attachment; filename={$filename}" ,'Expires' => '0' ,'Pragma' => 'public' ]; $resp = $this->getStream($recs->toArray(), $headers); return $resp->send(); } private function getStream($data, $headers){ $response = new StreamedResponse( function () use ($data) { $out = fopen('php://output', 'w'); foreach ($data as $row) { // $row must be string fputs($out, "{$row}\t"); } fclose($out); }, 200, $headers); return $response; } }
Ajax 에서
자세한 내용은 see also. 1 을 확인하자.
<?php class MyContorller extends Controller{ public function excelDeductPreInvest(Request $request){ $this->validate($request, [ // at this point, only 10, 11 digits of phone number is accepted 'product_idx' => 'bail|required|numeric', ]); $recs = ['name', 'id'] $out = ''; foreach ($recs as $row) { $out .= "{$row['name']}\t{$row['id']}\n"; } // encoding to CP949 $ansiOut = mb_convert_encoding($out, 'CP949'); return response()->json(['status' => 'success', 'data'=> [ "file" => "data:application/vnd.ms-excel;base64," .base64_encode($ansiOut)]]); } }
See Also
- ajax 로 excel download 하기 : php - PHPExcel download using ajax call - Stack Overflow
댓글 없음:
댓글 쓰기