利用Spire实现对Word模板的指定文字替换(文字、图片、表格)

简介: 利用Spire实现对Word模板的指定文字替换(文字、图片、表格)

1.安装Spire.Office

word文件内对要替换的地方用 [=xxx] 做标记

2.WordUtil.cs

using Spire.DataExport.XLS;
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using Spire.Doc.Formatting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
 
namespace zzzili
{    
    public class WordUtil
    {
        /// <summary>
        /// 定义word文档宽高
        /// </summary>
        private static float s_Page_Width = 500f;
        private static float s_Page_Height = 680f;
        /// <summary>
        /// Word 模板 替换
        /// <para>当前适用的字段模板形如:[=Name],其中 Name 就是字段名</para>
        /// <para>返回 true 表示成功</para>
        /// </summary>
        /// <param name="tempPath">Word 文件 模板路径</param>
        /// <param name="newWordPath">生成的新 Word 文件的路径</param>
        /// <param name="textDic">文字字典集合</param>
        /// <returns></returns>
        public static bool WordTemplateReplace(string tempPath, string newWordPath,
            WordReplace replace)
        {
            
                var doc = new Document(tempPath);  // 加载 Word 模板文件
 
                #region 字段替换文字
                var textreplacelist = replace.nodeList.Where(u=>u.type==WordReplace.EnumType.Text);
                foreach (var node in textreplacelist)
                {
                   
                        if (string.IsNullOrWhiteSpace(node.key))
                            continue;
                        if (string.IsNullOrWhiteSpace(node.value))
                            node.value = "";
                        doc.Replace(string.Format("[={0}]",node.key), node.value,true,true);  // 替换段落中的文字
                    
                }
 
                #endregion
 
                #region 字段替换为图片
                var imgreplacelist = replace.nodeList.Where(u => u.type == WordReplace.EnumType.Img);
                foreach (var node in imgreplacelist)
                {
                    if (string.IsNullOrWhiteSpace(node.key))
                        continue;
                    // 查找文档中的指定文本内容
                    TextSelection[] selections = doc.FindAllString(string.Format("[={0}]", node.key), true, true);
                    int index = 0;
                    TextRange range = null;
                    //遍历文档,移除文本内容,插入图片
                    foreach (TextSelection selection in selections)
                    {
                        DocPicture pic = new DocPicture(doc);
                        pic.LoadImage(node.value);
                        if (node.fixedType == WordReplace.EnumImgFixedType.FixedWidth)
                        {
                            //定宽
                            pic.Height = (s_Page_Width * pic.Height) / pic.Width;
                            pic.Width = s_Page_Width;
                        }
                        else
                        {
                            //定高
                            pic.Width = (s_Page_Height * pic.Width) / pic.Height;
                            pic.Height = s_Page_Height;
                        }
                        range = selection.GetAsOneRange();
                        index = range.OwnerParagraph.ChildObjects.IndexOf(range);
                        range.OwnerParagraph.ChildObjects.Insert(index, pic);
                        range.OwnerParagraph.ChildObjects.Remove(range);
                    }
                }
                #endregion
 
                #region 字段替换为Table
                var tablereplacelist = replace.nodeList.Where(u => u.type == WordReplace.EnumType.Table);
                foreach (var node in tablereplacelist)
                {
                    if (string.IsNullOrWhiteSpace(node.key))
                        continue;
 
                    ///组建表格
                    float cellWidth = s_Page_Width / node.table.rows[0].Count;
                    Table tb = doc.Sections[0].AddTable(true);
                    bool isHeader = true;
                    foreach (var row in node.table.rows)
                    {
                        var r = tb.AddRow(false,false);
                        foreach (var col in row)
                        {
                            var c = r.AddCell();
                            c.SetCellWidth(cellWidth, CellWidthType.Point);
                            TextRange textRange = c.AddParagraph().AppendText(col);
                            textRange.CharacterFormat.FontSize = 11;
                            textRange.CharacterFormat.FontName = "宋体";
                            if (isHeader == true)
                            {
                                textRange.CharacterFormat.Bold = true;//第一行字体加粗
                            }                            
                        }
                        isHeader = false;
                    }                    
 
                    //查找关键字符串文本
                    TextSelection[] selections = doc.FindAllString(string.Format("[={0}]", node.key), true, true);
                    foreach (var selection in selections)
                    {
                        //获取关键字符串所在段落的索引
                        TextRange range = selection.GetAsOneRange();
                        Paragraph paragraph = range.OwnerParagraph;
                        Body body = paragraph.OwnerTextBody;
                        int index = body.ChildObjects.IndexOf(paragraph);
                        //移除段落,插入表格 
                        body.ChildObjects.Remove(paragraph);
                        body.ChildObjects.Insert(index, tb);
                    }
                }
                #endregion
 
 
                doc.SaveToFile(newWordPath);
 
                return true;            
        }
 
        /// <summary>
        /// excel转为图片
        /// </summary>
        /// <param name="excelPath"></param>
        /// <param name="imgPath"></param>
        /// <returns></returns>
        public static bool ExcelToImg(string excelPath,string imgPath,int sheetIndex=0)
        {
            Spire.Xls.Workbook workbook = new Spire.Xls.Workbook();
            workbook.LoadFromFile(excelPath);
            Spire.Xls.Worksheet sheet = workbook.Worksheets[sheetIndex];
            sheet.SaveToImage(imgPath);
            return true;
        }
    }
}

3.WordReplace.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace zzzili
{
    public class WordReplace
    {
        public enum EnumType
        {
            Text = 1,
            Img = 2,
            Table=3
        }
        public enum EnumImgFixedType
        {
            FixedWidth=11,
            FixedHeight=12
        }
        public class WordReplaceNode
        {
            public string key { set; get; }
            public string value { set; get; }
            public ReplaceTable table { set; get; }
            public EnumType type { set; get; }
            public EnumImgFixedType fixedType { set; get; }
        }
        public class ReplaceTable
        {
            public List<List<string>> rows { set; get; }
            public ReplaceTable()
            {
                rows = new List<List<string>>();
            }
            public void addRow(List<string> row)
            {
                rows.Add(row);
            }
        }
        public List<WordReplaceNode> nodeList = new List<WordReplaceNode>();
 
        public void add(string _key, string _value)
        {
            var node = new WordReplaceNode();
            node.key = _key;
            node.value = _value;
            node.type = EnumType.Text;
            nodeList.Add(node);
        }
        public void add(string _key, string _value, EnumImgFixedType _fixedType)
        {
            var node = new WordReplaceNode();
            node.key = _key;
            node.value = _value;
            node.type = EnumType.Img;
            node.fixedType = _fixedType;
            nodeList.Add(node);
        }
        public void add(string _key,ReplaceTable _table)
        {
            var node = new WordReplaceNode();
            node.key = _key;
            node.type = EnumType.Table;
            node.table = _table;
            nodeList.Add(node);
        }
    }
}

4.调用示例

        static void Main(string[] args)
        {
            WordReplace replace = new WordReplace();
            //文字替换
            replace.add("test1", "河南省");//标记[=test1]
            //图片替换
            replace.add("img2", "C:\\102619.png", WordReplace.EnumImgFixedType.FixedWidth);//标记[=img2]
            //表格替换
            ReplaceTable tb = new ReplaceTable();
            tb.addRow(new List<string> { "序号","姓名","年龄" });
            tb.addRow(new List<string> { "1","张三","22" });
            tb.addRow(new List<string> { "2","李四","21" });
            replace.add("table3", tb);//标记[=table3]
 
            string temppath = "C:\\模板.docx";
            string newpath= "C:\\newfile.docx";         
            //word模板文字、图片、表格替换
            WordUtil.WordTemplateReplace(temppath, newpath, replace);
 
 
            //excel转图片
            string excelpath = "C:\\my.xlsx";
            string imgpath = "C:\\102619.png";            
            WordUtil.ExcelToImg(excelpath, imgpath);
 
            Console.WriteLine("ok....");            
        }
相关文章
|
8月前
|
JSON 测试技术 API
大模型工程师基础之学会使用openai
本系列教程涵盖OpenAI API基础到高级应用,包括文本生成、图像处理、语音交互、会话管理、流式响应、文件输入、推理模型及性能评估等十大核心功能。适合新手入门与工程师实践,助您掌握大模型开发关键技术。从简单Prompt设计到复杂多模态任务,逐步深入,结合实例代码与最佳实践,提升实际开发能力。希望这些内容对您有帮助!
826 11
|
安全 编译器 程序员
C# 中 foreach 循环和 for 循环深度比较
为什么建议你多数情况下使用 foreach 进行遍历循环?看完你就明白了
361 5
|
Java Maven 微服务
【Java用法】微服务之间的相互调用方式之一,通过FeignClient客户端调用其他微服务的方法
【Java用法】微服务之间的相互调用方式之一,通过FeignClient客户端调用其他微服务的方法
560 0
|
Java
java switch case多个条件
通过本文的介绍,我们详细探讨了Java中 `switch case`语句的多种用法和优化方法。从基本语法到合并多个条件,再到使用枚举、常量和函数优化,`switch case`语句在Java编程中提供了一种灵活且高效的控制流方式。掌握这些技巧,能够编写出更加简洁、可读性强的代码,提高开发效率和代码质量。希望本文能为您在实际开发中提供有价值的参考和指导。
1199 2
|
SQL 关系型数据库 MySQL
SQL自动启动设置指南:详细步骤与技巧
在数据库管理中,确保SQL服务能够自动启动对于保持数据服务的连续性和稳定性至关重要
|
网络协议 中间件 Python
使用代理IP的几种方案
使用代理IP的几种方案
454 2
|
消息中间件 Kafka
Kafka生产者和消费者相关命令行操作
Kafka生产者和消费者相关命令行操作
442 1
|
机器学习/深度学习 存储 人工智能
在 Visual Studio 2022 中使用 GitHub Copilot chat
本文通过实际应用场景和示例代码展示了 GitHub Copilot Chat 在 Visual Studio 2022 中的优势和特点。最后,鼓励读者在实际工作中尝试使用 Copilot Chat,以提升开发效率和代码质量。希望这些信息和经验能为你在使用GitHub Copilot时提供帮助和启发。
2540 1
在 Visual Studio 2022 中使用 GitHub Copilot chat
|
Java
Java【付诸实践 04】Jar包class文件反编译、修改、重新编译打包方法(含反编译工具jd-gui-windows-1.6.6.zip百度云资源)
Java【付诸实践 04】Jar包class文件反编译、修改、重新编译打包方法(含反编译工具jd-gui-windows-1.6.6.zip百度云资源)
2105 0
|
C# 数据安全/隐私保护
C# 窗体之间参数互相传递的两种方法与使用
C# 窗体之间参数互相传递的两种方法与使用

热门文章

最新文章