场景:项目需要将html页面转word文档
1.下载安装phpword插件composer require phpoffice/phpword
2.安装成功在tp目录下的vendor会出现phpoffice文件夹,说明下载成功
3.新建一个控制器Patrolreport(任意取名)并引入 对应的类,我在该控制器中创建了两个个方法index(模本替换),test(代码直接生成word)
<?php
/**
*
* 巡检报告生成
* Created by IntelliJ IDEA.
* User: Administrator
* Date: 2020/4/29
* Time: 10:18
*/
namespace app\api\controller;
use think\Controller;
use PhpOffice\PhpWord\IOFactory;
use PhpOffice\PhpWord\PhpWord;
use PhpOffice\PhpWord\TemplateProcessor; // 模板替换只需要引入这个类
class Patrolreport extends Controller
{
// 报告生成入口
public function index(){
$templateProcessor = new TemplateProcessor('./report/112.docx');
$templateProcessor -> setValue('enterprise',' xxxxx ');
$templateProcessor -> setValue('time',date("Y-m-d",time()));
$templateProcessor -> setValue('name','李xx科');
$templateProcessor -> setValue('cell','135xxxx884');
$templateProcessor -> setValue('adminname','xx明');
$dir = iconv("UTF-8", "GBK", "./report/".date('Y-m-d',time()).'/');//保存路径
if (!file_exists($dir)){
mkdir ($dir,0777,true); // 如果保存目录不存在就创建新目录
}
$filename = $dir.date('YmdHis',time()).'.docx';
$templateProcessor->saveAs($filename); //另存为新word文档,根据模板和变量生成了新的文档
// 下载文档
$file_dir = $filename; //下载文件存放目录
//检查文件是否存在
if (! file_exists ( $file_dir )) {
header('HTTP/1.1 404 NOT FOUND');
} else {
$file = fopen ( $file_dir, "rb" );//以只读和二进制模式打开文件
Header ( "Content-type: application/octet-stream" ); //告诉浏览器这是一个文件流格式的文件
Header ( "Accept-Ranges: bytes" ); //请求范围的度量单位
Header ( "Accept-Length: " . filesize ( $file_dir ) ); //Content-Length是指定包含于请求或响应中数据的字节长度
//用来告诉浏览器,文件是可以当做附件被下载,下载后的文件名称为$file_name该变量的值。
Header ( "Content-Disposition: attachment; filename=下载名称.docx" );
echo fread ( $file, filesize ( $file_dir ) ); //读取文件内容并直接输出到浏览器
fclose ( $file );
exit ();
}
}
// test
public function test(){
$PHPWord = new PhpWord();
// New portrait section
$section = $PHPWord->createSection();
$arr['project_name'] = '云桥';
$arr['buy_start_time'] = '20180515';
$arr['buy_end_time'] = '20190825';
$arr['start_s'] = '20190825';
$arr['end_s'] = '20190825';
$arr['total'] = 25;
$arr['tfee'] = 2500;
// Add text elements
$str = " ".$arr['project_name']."项目,与腾讯房产于".$arr['buy_start_time']."至".$arr['buy_end_time']."开展腾讯电商团购合作,".$arr['start_s']."至".$arr['end_s']."内,共计售出房屋". $arr['total']."套,成交明细见附件,收取服务费合计".$arr['tfee']."元,特此证明。";
$str5 = " 本确认函中的房源均已通过网签为确认标准,经双方授权代表签字后生效作为收款确认依据。且一旦签字盖章,乙方将不再承担该房源后续的电商团购费的退款责任。";
$str1 = "甲 方: 乙 方:";
$str2 = "授权代表签字: 授权代表签字:";
$str3 = "盖章: 盖章:";
$str4 = "签约时间:20 年 月 日 签约时间:20 年 月 日";
$title = '<h1>腾讯电商合作成交签约确认函</h1>';
$section->addText($title,'rStyle','pStyle');
$section->addTextBreak(2);
$section->addText($str,'cOntent');
$section->addTextBreak(2);
$section->addText($str5,'cOntent');
$section->addTextBreak(2);
// $section->addText(iconv('utf-8','GB2312//IGNORE',$str1),'cOntent');
// $section->addText(iconv('utf-8','GB2312//IGNORE',$str2),'cOntent');
// $section->addText(iconv('utf-8','GB2312//IGNORE',$str3),'cOntent');
// $section->addText(iconv('utf-8','GB2312//IGNORE',$str4),'cOntent');
$section->addText($str1,'cOntent');
$section->addText($str2,'cOntent');
$section->addText($str3,'cOntent');
$section->addText($str4,'cOntent');
$section->addTextBreak(2);
// $section->addText('I am inline styled.', array('name'=>'Verdana', 'color'=>'006699'));
$section->addTextBreak(2);
$PHPWord->addFontStyle('cOntent', array('bold'=>false, 'size'=>12));
$PHPWord->addFontStyle('rStyle', array('bold'=>true, 'italic'=>false, 'size'=>16,'align'=>'center'));
$PHPWord->addParagraphStyle('pStyle', array('align'=>'center', 'spaceAfter'=>100));
// $section->addText('I am styled by two style definitions.', 'rStyle', 'pStyle');
// $section->addText('I have only a paragraph style definition.', null, 'pStyle');
// Save File
$objWriter = IOFactory::createWriter($PHPWord, 'Word2007');
/*header("Content-Type: application/doc");
header("Content-Disposition: attachment; filename=".date("YmdHis").".doc");*/
$path = './report/'.date("YmdHis").'.doc';
$objWriter->save($path);
$file1 = fopen($path, "r");
// 输入文件标签
Header("Content-type: application/octet-stream");
Header("Accept-Ranges: bytes");
Header("Accept-Length:".filesize($path));
Header("Content-Disposition: attachment;filename=" . date("YmdHis").'.doc');
ob_clean(); // 重点!!!
flush(); // 重点!!!!可以清除文件中多余的路径名以及解决乱码的问题:
//输出文件内容
//读取文件内容并直接输出到浏览器
echo fread($file1, filesize($path));
fclose($file1);
exit();
}
}
4.index运行以后下载文件显示中文乱码
5.修改vendor->phpoffice->phpword->src->PhpWord->TemplateProcesssor.php,将
$replace = static::ensureUtf8Encoded($replace);删除或者注释掉,新增
$replace =iconv('gbk', 'utf-8', $replace);如下图
if (is_array($replace)) {
foreach ($replace as &$item) {
$item = static::ensureUtf8Encoded($item);
}
unset($item);
} else {
// $replace = static::ensureUtf8Encoded($replace);
$replace =iconv('gbk', 'utf-8', $replace);
}
6.运行结果