当前位置: 首页 > article >正文

C# 在Word文档模板中,按照占位符插入文字或图片

1,引入包:DocX

2,代码如下

  public class CC
  {

      public static void Ma22in()
      {
          // 示例:加载现有模板并替换占位符
          string templatePath = "报告模板.docx";  // 模板文件路径
          string outputPath = "Output.docx";      // 输出文件路径

          // 创建键值对,用于替换占位符
          var replacements = new Dictionary<string, string>()
          {
              ["{{name}}"] = "ExamineeModel.Name",
              ["{{hospitalName}}"] = "yyyy",
              ["{{age}}"] = "11",
              ["{{sex}}"] = "sex",
              ["{{date}}"] = $"{DateTime.Now:yyyy-MM-dd}",
              ["{{datetime}}"] = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss}",
              ["{{department}}"] = "devartName",
              ["{{checkDescription}}"] = "CheckDescription",
              ["{{conclusionAndAnalysis}}"] = "ConclusionAnalysis",
              ["{{doctorName}}"] = "DocterName",
          };

          // 创建图片集合,存储图片路径及对应的占位符
          var imagePaths = new Dictionary<string, List<string>>
  {
      { "{{image}}", new List<string>()
      {
          @"123222.jpg",
          @"123123.jpg",
          @"123123.jpg",
          @"123123.jpg",
      } } // 填写图片路径
  };

          ReplacePlaceholdersInTemplate(templatePath, outputPath, replacements, imagePaths);
      }

      public static void ReplacePlaceholdersInTemplate(string templatePath, string outputPath,
                                  Dictionary<string, string> replacements, Dictionary<string, List<string>> imagePaths)
      {
          using (DocX document = DocX.Load(templatePath))
          {

              // 替换文本占位符
              foreach (var replacement in replacements)
              {
                  foreach (Paragraph paragraph in document.Paragraphs)
                  {
                      if (paragraph.Text.Contains(replacement.Key))
                      {
                          paragraph.ReplaceText(replacement.Key, replacement.Value);
                      }
                  }
              }

              #region 眉头

              // 替换页眉中的文本占位符
              if (document.Headers.Even != null)
              {
                  foreach (Paragraph paragraph in document.Headers.Even.Paragraphs)
                  {
                      foreach (var replacement in replacements)
                      {
                          if (paragraph.Text.Contains(replacement.Key))
                          {
                              paragraph.ReplaceText(replacement.Key, replacement.Value);
                          }
                      }
                  }
              }

              if (document.Headers.First != null)
              {
                  foreach (Paragraph paragraph in document.Headers.First.Paragraphs)
                  {
                      foreach (var replacement in replacements)
                      {
                          if (paragraph.Text.Contains(replacement.Key))
                          {
                              paragraph.ReplaceText(replacement.Key, replacement.Value);
                          }
                      }
                  }
              }

              if (document.Headers.Odd != null)
              {

                  foreach (Paragraph paragraph in document.Headers.Odd.Paragraphs)
                  {
                      foreach (var replacement in replacements)
                      {
                          if (paragraph.Text.Contains(replacement.Key))
                          {
                              paragraph.ReplaceText(replacement.Key, replacement.Value);
                          }
                      }
                  }

              }
              #endregion

              // 替换图片占位符
              foreach (var imagePath in imagePaths)
              {
                  foreach (Paragraph paragraph in document.Paragraphs)
                  {
                      if (paragraph.Text.Contains(imagePath.Key))
                      {
                          InsertImage(paragraph, document, imagePath.Value);
                          paragraph.ReplaceText(imagePath.Key, "");
                      }
                  }
              }


              // 保存输出文档
              document.SaveAs(outputPath);
          }
      }

      public static void InsertImage(Paragraph paragraph, DocX document, List<string> imagePath2, float width = 150, float height = 200f)
      {
          foreach (var imagePath in imagePath2)
          {
              if (System.IO.File.Exists(imagePath))
              {
                  // 添加图片到文档
                  var image = document.AddImage(imagePath);
                  var picture = image.CreatePicture();

                  // 设置图片大小
                  //picture.SetSize(width, height);
                  picture.Width = width;
                  picture.Height = height;
                  // 在对应段落插入图片
                  paragraph.InsertPicture(picture);
                
              }
              else
              {

              }
          }
      }

  }

3,模板例如:
在这里插入图片描述


http://www.kler.cn/a/411983.html

相关文章:

  • Vue.js 中 v-bind 和 v-model 的用法与异同
  • 5.Feign与ReflectiveFeign
  • 51单片机从入门到精通:理论与实践指南入门篇(二)
  • JAVA---IO
  • JSON数据转化为Excel及数据处理分析
  • 【设计模式】【行为型模式(Behavioral Patterns)】之状态模式(State Pattern)
  • SQL server 计算同比和环比
  • PHP 类型比较
  • Qt上位机编程命名规范
  • 数字信号处理实验报告六:数字信号处理在多音频拨号系统中的应用
  • SpringBoot3与JUnit5集成测试
  • 100个python经典面试题详解(新版)
  • solr 远程命令执行 (CVE-2019-17558)
  • Cesium教程04_旋转模型
  • 每日刷题之优选算法(滑动窗口)
  • kali安装及使用docker和docker-compose
  • Go语言switch语句
  • 设计理念与数据反馈:面向火星熔岩管探索的跳跃机器人
  • Nodemailer使用教程:在Node.js中发送电子邮件
  • anaconda pycharm 使用问题
  • Python脚本检测网站是否开启浏览器缓存配置
  • FastDFS基础概述与系统架构详解
  • GitLab CI 配置
  • 深入浅出 WebSocket:构建实时数据大屏的高级实践
  • AdaPipe:通过自适应重新计算和细粒度的计算单元划分
  • Linux KASLR