function buildOutputSheet(array $data, $title, array $columns)
{
       $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
        $worksheet = $spreadsheet->getActiveSheet();
        $worksheet->setTitle($title);

        // write the cell header(the first row)
        $worksheet->fromArray([array_values($columns)], null, 'A1');
        // writing data
        foreach ($data as $row => $item) {
            foreach (array_keys($columns) as $col => $field) {
                $value = $item[$field];
                $worksheet->setCellValueByColumnAndRow($col + 1, $row + 2, $value);
            }
        }
        $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
        $filename = now()->format('Ymd-') . \Illuminate\Support\Str::random(6) . '.xlsx';
        // got the file store path.
        $file_path = storage_path("app/public") . "/$filename";
        // save to file.
        $writer->save($file_path);
}

标签: PHP, Excel

评论已关闭