TP5 + PHPWord導出word文檔中文出現亂碼的問題

場景:項目需要將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',' 重慶環問問科技有限公司 ');
        $templateProcessor -> setValue('time',date("Y-m-d",time()));
        $templateProcessor -> setValue('name','李正科');
        $templateProcessor -> setValue('cell','13500350884');
        $templateProcessor -> setValue('adminname','王加明');
        $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.運行結果

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章