由于phpexcel很久以前都已经停止维护了,所以目前用更加好的类库Spreadsheet,
上一篇说了怎么直接引入Spreadsheet到项目,今天说明一下怎么用Spreadsheet,下面以导出xlsx文档说明
// 首先实例化 Spreadsheet 对象 $spreadsheet = new Spreadsheet(); // 设置文档的基本属性 $spreadsheet->getProperties()->setCreator(APPLICATION_NAME)//创作者 ->setLastModifiedBy(APPLICATION_NAME)//最后更新者 ->setTitle(APPLICATION_NAME.'-数据统计')//属性标题 ->setSubject(APPLICATION_NAME.'-文档整理')//主题 ->setDescription('小V平台一个是集成微信系统、智能公众号、微官网、微商城、支付中台等功能的平台') ->setKeywords('小V平台,'.APPLICATION_NAME) ->setCategory('免费资源'); try{ //设置宽度 $spreadsheet->getActiveSheet()->getColumnDimension('A')->setWidth(25); $spreadsheet->getActiveSheet()->getColumnDimension('B')->setWidth(20); $spreadsheet->getActiveSheet()->getColumnDimension('C')->setWidth(20); $spreadsheet->getActiveSheet()->getColumnDimension('D')->setWidth(15); $spreadsheet->getActiveSheet()->getColumnDimension('E')->setWidth(22); $spreadsheet->getActiveSheet()->getColumnDimension('F')->setWidth(20); $spreadsheet->getActiveSheet()->getColumnDimension('G')->setWidth(30); $spreadsheet->getActiveSheet()->getColumnDimension('H')->setWidth(30); //设置行高度 $spreadsheet->getActiveSheet()->getRowDimension('1')->setRowHeight(22); $spreadsheet->getActiveSheet()->getRowDimension('2')->setRowHeight(20); //设置水平居中 $spreadsheet->getActiveSheet()->getStyle('A1')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER); //合并单元格 $spreadsheet->getActiveSheet()->mergeCells('A1:G1'); //设置数据,这样比较好在php里面遍历数据设置 $spreadsheet->setActiveSheetIndex(0)->setCellValue('单元格', '数据值'); //也支持连续设置值,这样适合不需要动态改变的数据 $spreadsheet->setActiveSheetIndex(0)->setCellValue('单元格1', '值1')->setCellValue('单元格2', '值2'); // 重命名表单 $spreadsheet->getActiveSheet()->setTitle('表单名称'); //设置一个激活状态(打开时选中状态),支持范围,默认0 $spreadsheet->setActiveSheetIndex(0); $file_name = '下载的文件名称';//设置文件名称 // 设置浏览器输出文件头header类型,这里是xlsx格式 header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); header('Content-Disposition: attachment;filename='.$file_name); header('Cache-Control: max-age=0'); //如果浏览器是IE9,则这里添加下面这句header header('Cache-Control: max-age=1'); //如果您是通过SSL服务于IE,那么可能需要以下内容 header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); header('Cache-Control: cache, must-revalidate'); // HTTP/1.1 header('Pragma: public'); // HTTP/1.0 $writer = IOFactory::createWriter($spreadsheet, 'Xlsx'); $writer->save('php://output'); exit; }catch (\PhpOffice\PhpSpreadsheet\Exception $e) { exit($e->getMessage()); }