之前有写过一篇phpexcel导出文件的文章,有需要的可以点击这里查看。这里只介绍phpspreadsheet的用法以及基本的文件导出功能。
安装非常简单,现在composer大行其道,只要使用命令
composer require phpoffice/phpspreadsheet
下载慢的更改为国内的镜像
composer config -g repo.packagist composer https://packagist.phpcomposer.com
删除之前的phpexcel插件(如果有的话)
composer remove phpoffice/phpexcel
这样准备工作就完成了
使用就更为简单了,比之前phpexcel的简化很多,这里只写一个示例代码
首先需要use两个文件,分别是
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
使用的方法为
public function printExcel($data) { $spreadsheet = new Spreadsheet(); /* @var $sheet \PhpOffice\PhpSpreadsheet\Writer\Xlsx\Worksheet */ $sheet = $spreadsheet->getActiveSheet(); $Letternum = 66; if ($data['title'] && \is_array($data['title'])) { foreach ($data['title'] as $datum) { $letternum = $Letternum++; $sheet->setCellValue(\chr($letternum).'1', $datum); } } if ($data['title']) { $sheet->setTitle($data['filename']); } $i = 0; foreach ($data['body'] as $k => $datum) { ++$i; $num = $k + 2; $Letternum = 66; foreach ($datum as $item) { $sheet->setCellValue(\chr(65).$num, $i); $letternum = $Letternum++; $sheet->setCellValue(\chr($letternum).$num, $item); } } // Create your Office 2007 Excel (XLSX Format) $writer = new Xlsx($spreadsheet); // Create a Temporary file in the system $fileName = $data['filename'].'.xlsx'; $temp_file = tempnam(sys_get_temp_dir(), $fileName); // Create the excel file in the tmp directory of the system $writer->save($temp_file); // Return the excel file as an attachment return $this->file($temp_file, $fileName, ResponseHeaderBag::DISPOSITION_INLINE); }
注意这里用了symfony的this->file方法,所以还需要引入框架的
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
并且继承AbstractController才可以使用
本文引用了
0 条评论