【问题标题】:edit docx file using phpword使用 phpword 编辑 docx 文件
【发布时间】:2016-03-06 05:35:25
【问题描述】:

是否可以使用 phpword 编辑现有的 docx 文件?

我想将页脚文本添加到我现有的 docx 文件中。

有很多示例,但这些示例是从头开始创建 doc 文件而不是编辑文件 有人可以链接到我的例子吗?谢谢你

就这样。

<?php
require_once 'PHPWord.php';
// New Word Document
$PHPWord = new PHPWord();
// New portrait section
$section = $PHPWord->createSection();
// Add header
$header = $section->createHeader();
$table = $header->addTable();
$table->addRow();
$table->addCell(4500)->addText('This is the header.');
$table->addCell(4500)->addImage('_earth.jpg', array('width'=>50, 'height'=>50, 'align'=>'right'));
// Add footer
$footer = $section->createFooter();
$footer->addPreserveText('Page {PAGE} of {NUMPAGES}.', array('align'=>'center'));
// Write some text
$section->addTextBreak();
$section->addText('Some text...');
// Save File
$objWriter = PHPWord_IOFactory::createWriter($PHPWord, 'Word2007');
$objWriter->save('HeaderFooter.docx');
?>

【问题讨论】:

    标签: php phpword


    【解决方案1】:

    是的,您可以编辑。

    来自文档

    PHPWord 是一个用纯 PHP 编写的库,它提供了一组 用于写入和读取不同文档文件格式的类。这 当前版本的 PHPWord 支持 Microsoft Office Open XML (OOXML 或 OpenXML),用于办公应用程序的 OASIS 开放文档格式 (OpenDocument 或 ODF)和富文本格式 (RTF)。

    其实是这样的

    1. 将我们现有的文件加载为模板。
    2. 编辑
    3. 保存

    从文档中,我找到了一个例子,

    <?php
    include_once 'Sample_Header.php';
    // Template processor instance creation
    echo date('H:i:s'), ' Creating new TemplateProcessor instance...', EOL;
    $templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor('resources/Sample_07_TemplateCloneRow.docx');
    // Variables on different parts of document
    $templateProcessor->setValue('weekday', htmlspecialchars(date('l'))); // On section/content
    $templateProcessor->setValue('time', htmlspecialchars(date('H:i'))); // On footer
    $templateProcessor->setValue('serverName', htmlspecialchars(realpath(__DIR__))); // On header
    // Simple table
    $templateProcessor->cloneRow('rowValue', 10);
    $templateProcessor->setValue('rowValue#1', htmlspecialchars('Sun'));
    $templateProcessor->setValue('rowValue#2', htmlspecialchars('Mercury'));
    $templateProcessor->setValue('rowValue#3', htmlspecialchars('Venus'));
    $templateProcessor->setValue('rowValue#4', htmlspecialchars('Earth'));
    $templateProcessor->setValue('rowValue#5', htmlspecialchars('Mars'));
    $templateProcessor->setValue('rowValue#6', htmlspecialchars('Jupiter'));
    $templateProcessor->setValue('rowValue#7', htmlspecialchars('Saturn'));
    $templateProcessor->setValue('rowValue#8', htmlspecialchars('Uranus'));
    $templateProcessor->setValue('rowValue#9', htmlspecialchars('Neptun'));
    $templateProcessor->setValue('rowValue#10', htmlspecialchars('Pluto'));
    $templateProcessor->setValue('rowNumber#1', htmlspecialchars('1'));
    $templateProcessor->setValue('rowNumber#2', htmlspecialchars('2'));
    $templateProcessor->setValue('rowNumber#3', htmlspecialchars('3'));
    $templateProcessor->setValue('rowNumber#4', htmlspecialchars('4'));
    $templateProcessor->setValue('rowNumber#5', htmlspecialchars('5'));
    $templateProcessor->setValue('rowNumber#6', htmlspecialchars('6'));
    $templateProcessor->setValue('rowNumber#7', htmlspecialchars('7'));
    $templateProcessor->setValue('rowNumber#8', htmlspecialchars('8'));
    $templateProcessor->setValue('rowNumber#9', htmlspecialchars('9'));
    $templateProcessor->setValue('rowNumber#10', htmlspecialchars('10'));
    // Table with a spanned cell
    $templateProcessor->cloneRow('userId', 3);
    $templateProcessor->setValue('userId#1', htmlspecialchars('1'));
    $templateProcessor->setValue('userFirstName#1', htmlspecialchars('James'));
    $templateProcessor->setValue('userName#1', htmlspecialchars('Taylor'));
    $templateProcessor->setValue('userPhone#1', htmlspecialchars('+1 428 889 773'));
    $templateProcessor->setValue('userId#2', htmlspecialchars('2'));
    $templateProcessor->setValue('userFirstName#2', htmlspecialchars('Robert'));
    $templateProcessor->setValue('userName#2', htmlspecialchars('Bell'));
    $templateProcessor->setValue('userPhone#2', htmlspecialchars('+1 428 889 774'));
    $templateProcessor->setValue('userId#3', htmlspecialchars('3'));
    $templateProcessor->setValue('userFirstName#3', htmlspecialchars('Michael'));
    $templateProcessor->setValue('userName#3', htmlspecialchars('Ray'));
    $templateProcessor->setValue('userPhone#3', htmlspecialchars('+1 428 889 775'));
    echo date('H:i:s'), ' Saving the result document...', EOL;
    $templateProcessor->saveAs('results/Sample_07_TemplateCloneRow.docx');
    echo getEndingNotes(array('Word2007' => 'docx'));
    if (!CLI) {
        include_once 'Sample_Footer.php';
    }
    

    现在看下面给出的代码行,如何访问现有的页眉和页脚

    $headers = $section->getHeaders();
    $header1 = $headers[1]; // note that the first index is 1 here (not 0)
    
    $elements = $header1->getElements();
    $element1 = $elements[0]; // and first index is 0 here normally
    
    // for example manipulating simple text information ($element1 is instance of Text object)
    $element1->setText("adding text here - old part: " . $element1->getText());
    
    $footers = $section->getFooters(); // to access footer
    

    您可以找到更多示例 here 。如果您想添加更多样式,请阅读此page。您还可以在他们的文档中看到一些recipes

    【讨论】:

      【解决方案2】:

      在您的文件(模板)docx 的页脚中,您可以放置​​一个像这样的变量 ${var1}。

      • 使用“TemplateProcessor”将文件作为模板打开。

        $templateObject = new TemplateProcessor($filename);
        
      • 替换文件中的 var1 变量

        $templateObject->setValue('var1', 'test');
        
      • 将您的模板转换为 PhpWord

        $fileName = $templateObject->save();
        $phpWordObject = IOFactory::load($fileName);
        unlink($fileName);
        return $phpWordObject;
        
      • 保存/呈现您的 phpWord 实例

        // create the writer
        $writer = $this->wordService->createWriter($phpWordObject, 'Word2007');
        // create the response
        $response = $this->wordService->createStreamedResponse($writer);
        // adding headers
        $dispositionHeader = $response->headers->makeDisposition(
            ResponseHeaderBag::DISPOSITION_ATTACHMENT,
            'export.docx'
        );
        $response->headers->set('Content-Type', 'application/msword');
        $response->headers->set('Pragma', 'public');
        $response->headers->set('Cache-Control', 'maxage=1');
        $response->headers->set('Content-Disposition', $dispositionHeader);
        

      【讨论】:

        【解决方案3】:

        可能对 Laravel 5 用户有用。您可以在控制器中使用它。

        public function wordDocumentFromWordTemplate() {
        
            $templateFile = public_path('templates') . '/template-file.docx';
            $templateObject = new TemplateProcessor($templateFile);
        
            $templateObject->setValue('var1', 'Text for var1');
        
            $wordDocumentFile = $templateObject->save();
        
            $headers = [
                'Content-Type' => 'application/msword',
                'Cache-Control' => 'max-age=0'
            ];
        
            return response()->download($wordDocumentFile, 'result.docx', $headers);
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-08-11
          • 1970-01-01
          • 2021-12-02
          • 2015-07-07
          • 2020-08-14
          相关资源
          最近更新 更多