引言
PHPWord是一个用纯PHP编写的库,它提供了一组用于读写不同文档文件格式的类。当前版本的PHPWord支持Microsoft Office Open XML(OOXML或OpenXML),用于Office应用程序的 OASIS 开放文档格式(OpenDocument或ODF),富文本格式(RTF),HTML和PDF。
github代码仓库
https://github.com/PHPOffice/PHPWord
安装phpsword
composer require phpoffice/phpword
phpword的用法文档手册
https://phpword.readthedocs.io/en/latest/
Class ‘ZipArchive’ not found
主要是因为linux操作系统缺少zip扩展引起来的
解决报错问题:
wget http://pecl.php.net/get/zip
tar -zxvf zip
yum remove libzip
wget https://libzip.org/download/libzip-1.5.2.tar.gz
tar -zxvf libzip-1.5.2.tar.gz
wget https://github.com/Kitware/CMake/releases/download/v3.15.4/cmake-3.15.4.tar.gz
tar -zxvf cmake-3.15.4.tar.gz
./bootstrap && make && sudo make install
mkdir build
cd build
cmake ..
make && make install
cd zip-1.19.0
phpize
./configure --with-php-config=/usr//local/bin/php-config
make
make install
vim /etc/php.ini
添加:
extension = zip.so
https://www.erro.com.cn/index/index/detail/id/51.html
在传统的fpm的运行模式下
/**
* 生成word
*/
public function testWord()
{
$phpWord = new \PhpOffice\PhpWord\PhpWord();
$section = $phpWord->addSection();
$section->addText(
'世界那么大,我向出去看一看'
);
$section->addText(
'世界那么大,我向出去看一看',
array('name' => 'Tahoma', 'size' => 10)
);
$fontStyleName = 'oneUserDefinedStyle';
$phpWord->addFontStyle(
$fontStyleName,
array('name' => 'Tahoma', 'size' => 10, 'color' => '1B2232', 'bold' => true)
);
$section->addText(
'世界那么大,我向出去看一看',
$fontStyleName
);
$fontStyle = new \PhpOffice\PhpWord\Style\Font();
$fontStyle->setBold(true);
$fontStyle->setName('Tahoma');
$fontStyle->setSize(13);
$myTextElement = $section->addText('世界那么大,我向出去看一看');
$myTextElement->setFontStyle($fontStyle);
$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
header('Content-Type: application/vnd.ms-word');
header('Content-Disposition: attachment;filename='.mt_rand(100,999).".docx");
header('Cache-Control: max-age=0');
$objWriter->save("php://output");
}
在fpm模式运行下,直接请求这个demo,就可以生成一个test.docx文件
在think-swoole的模式下运行
ob_start();
ob_clean();
$objWriter->save("php://output");
$content = ob_get_contents();
Response::header('Content-Type','application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; charset=utf-8')
->header('Content-Disposition','attachment;filename="123.docx"')
->content($content);
操作word文章参考:
https://www.cnblogs.com/phphuaibei/archive/2011/11/30/2269427.html