Spreadsheet学习

packagist地址
https://packagist.org/packages/phpoffice/phpspreadsheet

composer地址
composer require phpoffice/phpspreadsheet

导出表格

use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Alignment;

/**
     * 导出excel表格
     * @param $title
     * @param $heard
     * @param $data
     * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception
     */
    protected function export($title, $heard, $data)
    {
        require_once 'autoload.php';

        $spreadsheet = new Spreadsheet();

        //获取当前的excel表格
        $sheet = $spreadsheet->getActiveSheet();
        $sheet->setTitle($title);

        $letters = range('A', 'Z');
        foreach ($letters as $v) {
            $letters[] = 'A' . $v;
        }
        //水平居中
        $styleArray = [
            'alignment' => [
                'horizontal' => Alignment::HORIZONTAL_CENTER,
            ],
        ];
        //设置宽度
        $widths = [];
        foreach ($data as $k => $v) {
            foreach ($v as $ke => $va) {
                $sheet->getStyle($letters[$ke] . ($k + 2))->applyFromArray($styleArray);
                if (!isset($widths[$ke]) || (isset($widths[$ke]) && strlen($va) > $widths[$ke])) {
                    $widths[$ke] = strlen($va);
                }
                //防止手机号科学计数
                $sheet->setCellValue($letters[$ke] . ($k + 2), " " . $va . " ");
            }
        }
        foreach ($heard as $k => $v) {
            $sheet->getStyle($letters[$k] . '1')->applyFromArray($styleArray);
            if (strlen($v) > $widths[$k]) {
                $widths[$k] = strlen($v);
            }
            $sheet->getColumnDimension($letters[$k])->setWidth($widths[$k] + 4);
            $sheet->setCellValue($letters[$k] . '1', $v);
        }

        $file_name = $title . date('YmdHis') . ".xlsx";
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="'. $file_name .'"');
        header('Cache-Control: max-age=0');
        $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
        $writer->save('php://output');
    }

你可能感兴趣的:(学习,php)