phpword 模板替换并导出教程

phpword 模板替换并导出教程

word 模板文件定义

楼主在 public\uploads\application\template.docx 该路径下面创建了 word 的模板文件template.docx
该模板文件含有若干个形如 “ $ {baby_station} ” 的变量,这些变量就是用来在下面export方法中进行替换的。
注意:“$ {baby_station} ”这类变量应该在 sublime 类的编辑器中写好再复制粘贴进 word 文档中,不然word 可能无法编辑或者导致模板无法识别变量

PHPword 类库

类库链接:https://github.com/PHPOffice/PHPWord
我使用的是thinkphp5 框架,类库放在extend下面

控制器引入类库

use PhpOffice\Common\Font;
use PhpOffice\PhpWord\IOFactory;
use PhpOffice\PhpWord\PhpWord;
use PhpOffice\PhpWord\TemplateProcessor; // 模板替换只需要引入这个类

控制器export方法操作类库

/**
** phpword 模板替换并下载
**/
public function export()
{
  //指定模板文件
  $templateProcessor = new TemplateProcessor("uploads/application/template.docx");
  //通过setValue 方法给模板赋值
  $templateProcessor->setValue('baby_station', $baby_station);
  
  $dir = iconv("UTF-8", "GBK", "uploads/application/".date(Ymd).'/');//保存路径
  if (!file_exists($dir)){
       mkdir ($dir,0777,true);  // 如果保存目录不存在就创建新目录
   }
  $filename = $dir.date(YmdHis).'.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 ();
  }
}

模板替换只是 phpword 操作 word 的一种方式,另外一种是直接手写生成word文档的方式,有兴趣的欢迎私聊一起学习一下,或者我再抽空写一下另一种方式。

转载请注明出处,谢谢。

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
使用NPOI替换Word模板中的字段并导出可以分为以下几个步骤: 1. 引入NPOI库 首先,在项目中引入NPOI库。可以通过NuGet包管理器或手动下载DLL文件的方式引入。 2. 创建Word模板 创建一个Word模板,其中需要用到的字段用“占位符”表示,如“{{Name}}”、“{{Age}}”等等。 3. 加载Word模板 使用NPOI库打开Word模板。 ```csharp FileStream fs = new FileStream("模板.docx", FileMode.Open, FileAccess.ReadWrite); XWPFDocument doc = new XWPFDocument(fs); ``` 4. 替换模板中的字段 使用NPOI库中的`XWPFParagraph`类和`XWPFRun`类,遍历Word模板中的所有段落和文本,查找需要替换的字段,并进行替换。 ```csharp foreach (var para in doc.Paragraphs) { var text = para.Text; if (text.Contains("{{Name}}")) { text = text.Replace("{{Name}}", "张三"); para.ReplaceText("{{Name}}", "张三"); } if (text.Contains("{{Age}}")) { text = text.Replace("{{Age}}", "18"); para.ReplaceText("{{Age}}", "18"); } } ``` 5. 导出Word文档 使用NPOI库中的`XWPFDocument`类中的`Write`方法导出Word文档。 ```csharp using (FileStream fs = new FileStream("导出.docx", FileMode.Create, FileAccess.Write)) { doc.Write(fs); } ``` 完整示例代码如下: ```csharp using System.IO; using NPOI.XWPF.UserModel; namespace ConsoleApp { class Program { static void Main(string[] args) { //加载Word模板 FileStream fs = new FileStream("模板.docx", FileMode.Open, FileAccess.ReadWrite); XWPFDocument doc = new XWPFDocument(fs); //替换模板中的字段 foreach (var para in doc.Paragraphs) { var text = para.Text; if (text.Contains("{{Name}}")) { text = text.Replace("{{Name}}", "张三"); para.ReplaceText("{{Name}}", "张三"); } if (text.Contains("{{Age}}")) { text = text.Replace("{{Age}}", "18"); para.ReplaceText("{{Age}}", "18"); } } //导出Word文档 using (FileStream fs = new FileStream("导出.docx", FileMode.Create, FileAccess.Write)) { doc.Write(fs); } } } } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值