13
03月
2020
由于业务需要要读取excle模板写入,所以特地研究了一下
单纯的读取写入相当的简单
首先下载 官方有教程git方式 或者tp5下载
代码更简单(pass 我下载的时候看到可以直接运行,实际运行无效,实在运行不起来的不比尝试:跳过)
代码如下
public function dc(){ //模板所属位置 $template_path = '/www/wwwroot/文件目录/public/template/abc.xlsx'; $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($template_path); $worksheet = $spreadsheet->getActiveSheet(); //设置工作表标题名称 $worksheet->setTitle('学生成绩表'); //设置单元格内容 $worksheet->setCellValueByColumnAndRow(1, 1, '学生成绩表'); $worksheet->setCellValueByColumnAndRow(1, 2, '姓名'); $worksheet->setCellValueByColumnAndRow(2, 2, '语文'); $worksheet->setCellValueByColumnAndRow(3, 2, '数学'); $worksheet->setCellValueByColumnAndRow(4, 2, '外语'); $worksheet->setCellValueByColumnAndRow(5, 2, '总分'); //合并单元格 $worksheet->mergeCells('A1:E1'); $rows = Db::name('user')->select(); $len = count($rows); for ($i=0; $i < $len; $i++) { $j = $i + 3; //从表格第3行开始 $worksheet->setCellValueByColumnAndRow(1, $j, $rows[$i]['username']); $worksheet->setCellValueByColumnAndRow(2, $j, $rows[$i]['nickname']); $worksheet->setCellValueByColumnAndRow(3, $j, $rows[$i]['mobile']); $worksheet->setCellValueByColumnAndRow(4, $j, $rows[$i]['level']); $worksheet->setCellValueByColumnAndRow(5, $j, $rows[$i]['bio']); } $filename = '成绩表.xlsx'; header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); header('Content-Disposition: attachment;filename="'.$filename.'"'); header('Cache-Control: max-age=0'); $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx'); $writer->save('php://output');}
代码简单 直接复制粘贴直接干 官方资料地址:https://phpspreadsheet.readthedocs.io/en/latest/topics/reading-and-writing-to-file/#openlibre-office-ods