关于laravel:Laravel导出CSV

48次阅读

共计 865 个字符,预计需要花费 3 分钟才能阅读完成。

Laravel 导出 CSV

<?php

namespace App\Services;

use Symfony\Component\HttpFoundation\BinaryFileResponse;

class ReportsBase
{
    /**
     * 写入 CSV 文件
     * @param string $file_name
     * @param array $arrHeader
     * @param array $arrDataList
     * @return array
     */
    public static function writeFile(string $file_name = '', array $arrHeader = [], array $arrDataList = []): array
    {ini_set('memory_limit', '2048M');
        $dir_name  = 'export/';
        $file_name = $dir_name . sprintf("%s", $file_name . ".csv");
        $fileData  = implode(',', $arrHeader) . "\r\n";
        foreach ($arrDataList as $line) {$fileData .= implode(',', str_replace(',', '', $line)) ."\r\n";
        }
        \Storage::disk('local')->put($file_name, mb_convert_encoding($fileData, 'gbk', 'utf-8'));

        return [
            'file_path' => $dir_name,
            'file_name' => storage_path('app/' . $file_name),
        ];
    }

    /**
     * 下载文件
     * @param $file
     * @return BinaryFileResponse
     */
    public static function downloadCsv($file): BinaryFileResponse
    {return response()->download($file)->deleteFileAfterSend();}
}

正文完
 0