您的当前位置:首页>全部文章>文章详情

PHP 使用phpspreadsheet 导出支付宝批量付款的excel教程

发表于:2023-05-29 22:34:58浏览:444次TAG: #PHP #phpspreadsheet
composer require phpoffice/phpspreadsheet


use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;


$title = ['序号(必填)', '收款方支付宝账号(必填)','收款方姓名(必填)', '金额(必填,单位:元)','备注(选填)'];
        $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        $sheet->mergeCells('A1:E1');
        $sheet->setCellValue('A1', "支付宝批量付款文件模板(前面两行请勿删除)");
        $styleArray = [
          'alignment' => [
            'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
          ],
        ];
       $sheet->getStyle('A1')->applyFromArray($styleArray);
         foreach ($title as $key => $value) {
            $sheet->setCellValueByColumnAndRow($key +1, 2, $value);
        }
        $data = [
        ['title1' => '111', 'title2' => '222'],
        ['title1' => '111', 'title2' => '222'],
        ['title1' => '111', 'title2' => '222']
    ];
         $row = 3; // 从第二行开始
        foreach ($data as $item) {
            $column = 1;
            foreach ($item as $value) {
                // 单元格内容写入
                $sheet->setCellValueByColumnAndRow($column, $row, $value);
                $column++;
            }
            $row++;
        }

        // Redirect output to a client’s web browser (Xlsx)
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename='.date('Y-m-d H:i:s',time()).".xlsx");
        header('Cache-Control: max-age=0');
        // If you're serving to IE 9, then the following may be needed
        header('Cache-Control: max-age=1');

        // If you're serving to IE over SSL, then the following may be needed
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
        header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header('Pragma: public'); // HTTP/1.0
        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
        $writer->save('php://output');
        exit;