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,模板例如: