phpoffice create excel and download

Solutions on MaxInterview for phpoffice create excel and download by the best coders in the world

showing results for - "phpoffice create excel and download"
Yasmina
30 Feb 2017
1use PhpOffice\PhpSpreadsheet\Spreadsheet;
2use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
3
4class DownloadExcel
5{
6    public static function createExcel(array $data, array $headers = [],
7                                       $fileName = 'data.xlsx')
8    {
9        $spreadsheet = new Spreadsheet();
10        $sheet = $spreadsheet->getActiveSheet();
11
12        for ($i = 0, $l = sizeof($headers); $i < $l; $i++) {
13            $sheet->setCellValueByColumnAndRow($i + 1, 1, $headers[$i]);
14        }
15
16        for ($i = 0, $l = sizeof($data); $i < $l; $i++) { // row $i
17            $j = 0;
18            foreach ($data[$i] as $k => $v) { // column $j
19                $sheet->setCellValueByColumnAndRow($j + 1, ($i + 1 + 1), $v);
20                $j++;
21            }
22        }
23
24        $writer = new Xlsx($spreadsheet);
25        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
26        header('Content-Disposition: attachment; filename="'. urlencode($fileName).'"');
27        $writer->save('php://output');
28    }
29
30}
31