PhpSpreadsheet 匯出excel範例

cwfan發表於2021-03-17
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);
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章