PhpOffice\PhpSpreadsheet不但可以操作Excel和导出Excel,也可以用来导出pdf文件。不过需要安装扩展,Tcpdf/Dompdf等三方类库,否则提示类库不存在。
安装phpspreadsheet
安装tcpdf
设置支持中文
安装phpspreadsheet
composer require phpoffice/phpspreadsheet
安装tcpdf
用来导出pdf文件
composer require tecnickcom/tcpdf
因为环境已安装phpspreadsheet就不再展示。
安装tcpdf
创建xls模板用于导出pdf
$key = ['id', 'product_name', 'product_desc', 'optionsNo', 'created_at'];
$data = Db::name('product')
->order('id', 'asc')
->field($key)->limit(0, 10)->select()->toArray();
foreach ($data as &$v) {
$v['created_at'] = date('Y/m/d H:i:s', $v['created_at']);
unset($v);
加载模板文件并赋值文件内容
$spreadsheet = IOFactory::load('./uploads/test1.xlsx');
$sheet = $spreadsheet->getActiveSheet();
// 处理标题 因为合并了 使用A1即可赋值
$sheet->setCellValue('A1', '产品导出数据');
// 处理内容从第三行开始
$row = 3;
foreach ($data as $item) {
$column = 1;
foreach ($item as $value) {
$sheet->setCellValueByColumnAndRow($column, $row, $value);
$column++;
$row++;
文件下载使用tcpdf扩展生成pdf文件
$pdf = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Tcpdf');
设置支持中文
设置字体 stsongstdlight支持中文
$pdf->SetFont('stsongstdlight', '', 10);
$filename = './uploads/product1.pdf';
$pdf->save($filename);
PhpSpreadsheet操作Excel文件很方便,还有很多操作没有举例,有需要的可查看官网。
如果安装的Tcpdf不支持中文,上述中文设置也没有效果,可以查看这篇文章。
PHP TCPDF导出支持中文的pdf_JSON_L的博客-CSDN博客
//wkhtmltopdf 这里需要替换成你自己的安装位置
localhost:bin test$ wkhtmltopdf http://www.qq.com //users/yehua/desktop...
2019年10月11日09:32:33
官方使用文档https://phpspreadsheet.readthedocs.io/en/stable/topics/accessing-cells/
api文档https://phpoffice.github.io/PhpSpreadsheet/master/PhpOffice.html
翻译的是使用文档,机翻+校验,因为现在单个文档内容放的东...
不过他也支持pdf 哦、不过需要依赖于MPDF或者tcpdf或者dompdf
1、导出(可以导出为pdf、xls、xlsx等)
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\IOFactory;
* [数据导出]
* @return [type] [description]
从不包含格式信息的文件(例如CSV文件)中加载数据时,数据将以字符串或数字(浮点数或整数)的形式读取。这意味着PhpSpreadsheet不会自动将日期/时间(例如或13:30),布尔值(true或false),百分比(75%),超链接()等识别为简单字符串以外的任何内容。但是,可以在Value Binder的加载过程中应用针对这些值执行的其他处理。值绑定器是实现接口的类。它必须包含一个接受a和一个值作为参数的方法,并返回一个布尔值true或false指示是否已使用该值填充工作簿单元格。
把代码放到了github上,点击进入
前阶段有个项目用到了线上预览功能,
关于预览office文件实现核心就是,把office文件(word,excel,ppt)转为pdf文件,
然后再把pdf文件经过pdf2html转为html文件进行预览。
利用openoffice的话,非常简单,不过效果不太好,转成的pdf样式会乱!
这里就不做介绍了。
下面我把office文件转为pdf步骤写一
laravel怎么可以把excel文件转为pdf文件?尝试用PHPOffice/PhpSpreadsheet转换,写了个函数,如下:备注:PhpSpreadsheet是PHPExcel的新版,https://github.com/PHPOffice/...public function makePdf(){$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFac...
PHPExcel[1]已经废弃,现在用PhpSpreadsheet[2],官方文档。
PhpSpreadsheet是一个用纯PHP写的类库,可以读写操作不同的电子表格文件格式,像Excel和LibreOffice。
支持的文档格式: