利用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....");            
        }
相关文章
Word处理控件Spire.Doc常见问题解答
为方便使用者快速掌握和了解Spire.Doc,本文列举了Word处理控件Spire.Doc常见问题及解答欢迎下载体验!
|
Java API Apache
Gradle从0入门到实战系列【一】Hello World Gradle
早期没有项目管理工具时,对于项目所依赖的第三方包采用的是:拷贝三方jar包到本地,然后加入到lib目录下,这样做劣势不言而喻,管理复杂容易冲突。 Gradle是一个基于Apache Ant和Apache Maven概念的项目自动化构建开源工具。它使用一种基于Groovy的特定领域语言(DSL)来声明项目设置,也增加了基于Kotlin语言的kotlin-based DSL,抛弃了基于XML的各种繁琐配置。面向Java应用为主。
982 0
Gradle从0入门到实战系列【一】Hello World Gradle
|
XML Java Apache
Java 生成PDF文档
最近项目需要实现PDF下载的功能,由于没有这方面的经验,从网上花了很长时间才找到相关的资料。整理之后,发现有如下几个框架可以实现这个功能。 1. 开源框架支持 iText,生成PDF文档,还支持将XML、Html文件转化为PDF文件; Apache PDFBox,生成、合并PDF文档; docx4j,生成docx、pptx、xlsx文档,支持转换为PDF格式。
11791 1
|
消息中间件 安全 API
C#实现操作Windows窗口句柄:SendMessage/PostMessage发送系统消息、事件和数据【窗口句柄总结之二】
SendMessage/PostMessage API 可以实现发送系统消息,这些消息可以定义为常见的鼠标或键盘事件、数据的发送等各种系统操作......
7918 1
C#实现操作Windows窗口句柄:SendMessage/PostMessage发送系统消息、事件和数据【窗口句柄总结之二】
|
11月前
|
API 开发工具 Android开发
【01】完整开发即构美颜sdk的uni官方uts插件—让所有开发者可以直接使用即构美颜sdk的能力-优雅草卓伊凡
【01】完整开发即构美颜sdk的uni官方uts插件—让所有开发者可以直接使用即构美颜sdk的能力-优雅草卓伊凡
433 23
【01】完整开发即构美颜sdk的uni官方uts插件—让所有开发者可以直接使用即构美颜sdk的能力-优雅草卓伊凡
|
Kubernetes Linux 容器
如何在centos中关闭swap分区
在CentOS中,关闭swap分区可以通过临时关闭和永久禁用两种方式实现。临时关闭swap分区适用于临时测试和故障排除,而永久禁用swap分区则需要修改 `/etc/fstab`文件。通过遵循上述步骤,可以确保系统在没有swap的情况下稳定运行。这对于某些应用场景(如Kubernetes集群)是必要的配置步骤。
1400 3
|
数据采集 数据可视化 数据挖掘
基于python django的scrapy去哪儿网数据采集与分析,包括登录注册和可视化大屏,有md5加密
本文介绍了一个基于Python和Django框架,使用Scrapy进行去哪儿网数据采集与分析的项目,包括实现登录注册功能、MD5加密以及通过可视化大屏展示分析结果的综合系统。
232 1
基于python django的scrapy去哪儿网数据采集与分析,包括登录注册和可视化大屏,有md5加密
|
传感器 运维 算法
基于stm32的多旋翼无人机(Multi-rotor UAV based on stm32)(中)
基于stm32的多旋翼无人机(Multi-rotor UAV based on stm32)(中)
491 0
|
JavaScript API 开发者
Vue 3 为什么同时需要 Ref 和 Reactive?
Vue 3 为什么同时需要 Ref 和 Reactive?
|
运维 监控 数据可视化
高效运维的秘密武器:自动化工具链的构建与实践在当今数字化时代,IT系统的复杂性和规模不断增加,使得传统的手动运维方式难以应对日益增长的业务需求。因此,构建一套高效的自动化工具链成为现代运维的重要任务。本文将深入探讨如何通过自动化工具链提升IT运维效率,确保系统稳定运行,并实现快速响应和故障恢复。
随着企业IT架构的不断扩展和复杂化,传统的手动运维已无法满足业务需求。自动化工具链的构建成为解决这一问题的关键。本文介绍了自动化工具链的核心概念、常用工具及其选择依据,并通过实际案例展示了自动化工具链在提升运维效率、减少人为错误、优化资源配置等方面的显著效果。从监控系统到自动化运维平台,再到持续集成/持续部署(CI/CD)的流程,我们将一步步揭示如何成功实施自动化工具链,助力企业实现高效、稳定、可靠的IT运维管理。

热门文章

最新文章