thinkphp6 导出word文件(包含html、css)
首先使用composer下载相关插件
composer require phpoffice/phpword
<?php
namespace app\controller;
use PhpOffice\PhpWord\PhpWord;
use PhpOffice\PhpWord\IOFactory;
use PhpOffice\PhpWord\Settings;
class WordController
{
public function export()
{
// 创建一个新的Word文档对象
$phpWord = new PhpWord();
// 添加一个段落,并设置样式
$section = $phpWord->addSection();
$section->addText('Hello World!', ['bold' => true, 'size' => 20]);
// 添加HTML内容
$html = '<p style="color: red;">This is a red paragraph.</p>';
$dom = new \DOMDocument();
$dom->loadHTML('<?xml encoding="UTF-8">' . $html);
$paragraphs = $dom->getElementsByTagName('p');
foreach ($paragraphs as $paragraph) {
$text = $paragraph->nodeValue;
$section->addText($text, ['color' => 'red']);
}
// 导出Word文件
$filename = 'export.docx';
$phpWord->save($filename, 'Word2007');
// 下载导出的文件
header('Content-Disposition: attachment; filename="' . $filename . '"');
readfile($filename);
unlink($filename);
}
}