PhpSpreadsheet导入导出excel

封装一个类:

load($tmp);
        $sheetData = $spreadsheet->getActiveSheet()->toArray(null, true, true, true);
        var_dump($sheetData);exit;
        
    }


    /**
     * 导出excel
     */
    public function arrayToXlsx($data,$title){

        $spreadsheet = new Spreadsheet();
        $worksheet = $spreadsheet->getActiveSheet();

        //设置工作表标题名称
        $worksheet->setTitle('工作表格1');

        //表头 设置单元格内容
        foreach ($title as $key => $value) {
            $worksheet->setCellValueByColumnAndRow($key+1, 1, $value);
        }

        $row = 2; //从第二行开始
        foreach ($data as $item) {
            $column = 1; //从第一列设置并初始化
            foreach ($item as $value) {
                $worksheet->setCellValueByColumnAndRow($column, $row, $value); //哪一列哪一行设置哪个值
                $column++; //列数加1
            }
            $row++; //行数加1
        }

        //输出到浏览器
        $fileName = date('YmdHis',time());
        $fileType = 'Xlsx';
        $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
        $this->excelBrowserExport($fileName, $fileType);
        $writer->save('php://output');

    }

    public function excelBrowserExport($fileName, $fileType) {
        //文件名称校验
        if(!$fileName) {
            throw new Exception('文件名不能为空');
        }

        //Excel文件类型校验
        $type = ['Excel2007', 'Xlsx', 'Excel5', 'xls'];
        if(!in_array($fileType, $type)) {
            throw new Exception('未知文件类型');
        }

        if($fileType == 'Excel2007' || $fileType == 'Xlsx') {
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header('Content-Disposition: attachment;filename="'.$fileName.'.xlsx"');
            header('Cache-Control: max-age=0');
        } else {
            header('Content-Type: application/vnd.ms-excel');
            header('Content-Disposition: attachment;filename="'.$fileName.'.xls"');
            header('Cache-Control: max-age=0');
        }
    }
}

导出调用:

$data = [
            [1, 'jack', 10],
            [2, 'mike', 12],
            [3, 'jane', 21],
            [4, 'paul', 26],
            [5, 'kitty', 25],
            [6, 'yami', 60],
        ];

$title = ['id', 'name', 'age'];
$MyPhpSpreadsheet = new MyPhpSpreadsheet();
$MyPhpSpreadsheet->arrayToXlsx($data,$title);

导入调用:

前端input type='file' 上传 ,后端读取$_FILES

 

参考:https://www.cnblogs.com/itbsl/p/10369695.html

 

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