精华内容
下载资源
问答
  • Free Spire.Doc for Java 是一款免费、专业的 Java Word 组件,开发人员使用它可以轻松地将 Word 文档创建、读取、编辑、转换和打印等功能集成到自己的 Java 应用程序中。作为一款完全独立的组件,Free Spire.Doc ...

    简介

    Free Spire.Doc for Java 是一款免费、专业的 Java Word 组件,开发人员使用它可以轻松地将 Word 文档创建、读取、编辑、转换和打印等功能集成到自己的 Java 应用程序中。作为一款完全独立的组件,Free Spire.Doc for Java的运行环境无需安装 Microsoft Office。
    官网地址:点击跳转

    集成步骤

    直接新建一个springboot项目进行操作

    加入依赖

    也可以去官网下载jar包

            <dependency>
                <groupId>e-iceblue</groupId>
                <artifactId>spire.doc.free</artifactId>
                <version>3.9.0</version>
            </dependency>
            
            <repositories>
    	        <repository>
    	            <id>com.e-iceblue</id>
    	            <url>https://repo.e-iceblue.cn/repository/maven-public/</url>
    	        </repository>
    	    </repositories>
    
    工具类
    import com.spire.doc.Document;
    import com.spire.doc.FileFormat;
    import com.spire.doc.documents.BookmarksNavigator;
    import com.spire.doc.documents.Paragraph;
    import com.spire.doc.documents.TextWrappingStyle;
    import com.spire.doc.fields.DocPicture;
    
    /**
     * @Author: CTW
     * @Date: create in 2021/9/21
     */
    public class FreeSpireUtil {
    
        /**
         * 替换word
         *
         * @param path word所在路径
         * @return 替换后的word所在路径
         */
        public static String replaceWord(String path) {
            //加载包含书签的模板文档
            Document doc = new Document();
            doc.loadFromFile(path);
            
            //定位到指定书签位置末尾标签位置,插入文本
            BookmarksNavigator bookmarksNavigator1 = new BookmarksNavigator(doc);
            bookmarksNavigator1.moveToBookmark("test1");
            bookmarksNavigator1.insertText("这是我在test1尾部插入的内容!");
            //定位到指定书签位置,文本替换掉书签
            BookmarksNavigator bookmarksNavigator2 = new BookmarksNavigator(doc);
            bookmarksNavigator2.moveToBookmark("test2");
            bookmarksNavigator2.replaceBookmarkContent("我把test2给替换了!", true);
            //定位到指定书签位置起始标签位置,插入图片
            BookmarksNavigator bookmarksNavigator3 = new BookmarksNavigator(doc);
            bookmarksNavigator3.moveToBookmark("test3");
            Paragraph para = new Paragraph(doc);
            DocPicture picture = para.appendPicture("D:\\MyCode\\combat\\free-spire\\src\\main\\resources\\word\\springboot.jpeg");
            picture.setWidth(100f);
            picture.setHeight(100f);
            picture.setTextWrappingStyle(TextWrappingStyle.Through);
            bookmarksNavigator3.insertParagraph(para);
    
            //保存文档,返回前端访问
            String url = "D:\\MyCode\\combat\\free-spire\\src\\main\\resources\\word\\test_" + System.currentTimeMillis() + ".docx";
            doc.saveToFile(url, FileFormat.Doc);
            //关闭资源
            doc.dispose();
            return url;
        }
    
        public static void main(String[] args) {
            String path = "D:\\MyCode\\combat\\free-spire\\src\\main\\resources\\word\\test.docx";
            String wordPath = replaceWord(path);
            System.out.println("替换后文档所在路径:" + wordPath);
        }
    
    word编辑
    1. 新建一个文档,test(n)是书签
      在这里插入图片描述
    2. 通过书签替换占位符
      在这里插入图片描述
    3. 替换添加完了,保存即可
    运行工具类中的main方法进行测试

    在这里插入图片描述

    附:

    关于Free Spire,还有许多强大的功能,可以看看中文文档:点击跳转

    展开全文
  • java替换word占位符.zip

    2021-07-26 13:58:06
    java 替换word 占位符
  • I have a template in word (.docx) format and want to replace some placeholders in this template with my own data, do you know where I can find the right classes for this project? It would be nice for ...

    I have a template in word (.docx) format and want to replace some placeholders in this template with my own data, do you know where I can find the right classes for this project? It would be nice for me to know the namespace. Are there any newer classes for handling word documents in the docx format (xml) than the com classes? Thank you for all your answers, I hope someone can help me with my problem.

    greets

    Sebastian

    解决方案

    The new office formats (docx, xlsx, etc) are zip files that contain a collection of xml files. With that in mind you have a couple of approaches.

    You can unzip the docx file, do a search and replace for your tokens, and zip it back up.

    There is a website at openxmldeveloper.org that is just for this kind of thing. Also, bear in mind that they are already shipping a beta version 2 of the SDK.

    展开全文
  • 1】excel的占位符替换 效果如图 关键代码: ///savedFilePath需要保存的路径 templateDocPath模板路径 替换的关键字和值 格式 [姓名]$%$小王 public static void ReadExcel(string savedFilePath, ...

    1】excel的占位符替换

    效果如图

     

    关键代码:

    ///savedFilePath需要保存的路径  templateDocPath模板路径  替换的关键字和值  格式  [姓名]$%$小王
    public static void ReadExcel(string savedFilePath, string templateDocPath,  List<string> ReArray)
            {
    
                try
                {
                    //加载可读可写文件流 
                    using (FileStream stream = new FileStream(templateDocPath, FileMode.Open, FileAccess.Read))
                    {
                        IWorkbook workbook = WorkbookFactory.Create(stream);//使用接口,自动识别excel2003/2007格式
                        ISheet sheet = workbook.GetSheetAt(0);//得到里面第一个sheet
                        IRow row = null;
                        ICell cell = null;
    
                        //1读取符合条件的
                        Regex reg = new Regex(@"\[\S+?\]", RegexOptions.Singleline);
                        List<string> getList = new List<string>();
                        for (int i = sheet.FirstRowNum; i <= sheet.LastRowNum; i++)
                        {
                            row = sheet.GetRow(i);
                            for (int j = row.FirstCellNum; j < row.LastCellNum; j++)
                            {
                                cell = row.GetCell(j);
                                if (cell != null)
                                {
                                    if (cell.CellType == NPOI.SS.UserModel.CellType.String)
                                    {
                                        var currentCellVal = cell.StringCellValue;
                                        if (reg.IsMatch(currentCellVal))
                                        {
                                            MatchCollection listsCollection = reg.Matches(currentCellVal);
                                            for (int jNum = 0; jNum < listsCollection.Count; jNum++)
                                            {
                                                var aa = listsCollection[jNum].Value;
                                                getList.Add(aa);
                                            }
                                        }
                                    }
                                }
    
                            }
                        }
    
    
                        //2替换
    
                        for (int i = sheet.FirstRowNum; i <= sheet.LastRowNum; i++)
                        {
                            row = sheet.GetRow(i);
                            for (int j = row.FirstCellNum; j < row.LastCellNum; j++)
                            {
    
                                cell = row.GetCell(j);
                                if (cell != null)
                                {
                                    foreach (var item in getList)
                                    {
                                        string getX = cell.StringCellValue;
                                        if (getX.Contains(item))
                                        {
                                            foreach (var itemRa in ReArray)
                                            {
    
                                                var getValue = itemRa.Split(new string[] { "$%$" }, StringSplitOptions.None);
                                                if (item == getValue[0])
                                                {
                                                    getX = getX.Replace(item, getValue[1]);
                                                    cell.SetCellValue(getX);
                                                }
    
                                            }
    
                                        }
                                    }
                                    //删除没有的数据   此处是excel中需要替换的关键字,但是数据库替换中却没有的,用空值代替原来“[关键字]”
                                    string getXNull = cell.StringCellValue;
                                    MatchCollection listsCollection = reg.Matches(getXNull);
                                    if (listsCollection.Count > 0)
                                    {
                                        var valNull = getXNull;
                                        getXNull = getXNull.Replace(valNull, "");
                                        cell.SetCellValue(getXNull);
                                    }
    
    
    
    
    
                                }
                            }
                        }
                        //新建一个文件流,用于替换后的excel保存文件。
                        FileStream success = new FileStream(savedFilePath, FileMode.Create);
                        workbook.Write(success);
                        success.Close(); 
                    }
    
    
                }
                catch (Exception ex)
                {
                }
                finally
                {
                }
            }
    View Code

     

    2】word的占位符替换

     /// <summary>
            /// world自定义模板导出
            /// </summary>
            /// <param name="savedFilePath">保存路劲</param>
            /// <param name="templateDocPath">获取模板的路径</param>
            /// <param name="ReArray">需要替换的值    [姓名]$%$张三</param> 
            /// 
            public static void ReadWord(string savedFilePath, string templateDocPath, List<string> ReArray)
            {
    
                try
                {
                    #region 进行替换
    
    
                    Aspose.Words.Document doc = new Aspose.Words.Document(templateDocPath);
                    DocumentBuilder builder = new DocumentBuilder(doc);
                    foreach (var item in ReArray)
                    {
                        var reA = item.Split(new string[] { "$%$" }, StringSplitOptions.None);
                        string oneValue = reA[0];
                        string towValue = ToDBC(reA[1]).Replace("\r", "<br/>");//\r和中文符号必须替换否则报错
                        doc.Range.Replace(oneValue, towValue, false, false);
                    }
                    doc.Save(savedFilePath);//也可以保存为1.doc 兼容03-07 
    
                    #endregion
    
                }
                catch (Exception ex)
                {
    
                    throw;
                }
            }
    View Code

    3】excel的占位符替换=》多字段

    效果图

            /// <summary>
            /// 根据模版导出Excel
            /// </summary>
            /// <param name="templateFile">模版路径(包含后缀)  例:"/Template/Exceltest.xls"</param>
            /// <param name="strFileName">文件名称(不包含后缀)  例:"Excel测试"</param>
            /// <param name="source">源DataTable</param>
            /// <param name="cellKes">需要导出的对应的列字段  例:string[] cellKes = { "name","sex" };</param>
            /// <param name="rowIndex">从第几行开始创建数据行,第一行为0</param>
            /// <returns>是否导出成功</returns>
            public static string ExportScMeeting(string templateFile, string strFileName, DataTable source, List<string> cellKes, int rowIndex)
            {
                templateFile = HttpContext.Current.Server.MapPath(templateFile);
                int cellCount = cellKes.Count();//总列数,第一列为0
                IWorkbook workbook = null;
                try
                {
                    using (FileStream file = new FileStream(templateFile, FileMode.Open, FileAccess.Read))
                    {
    
    
                        workbook = WorkbookFactory.Create(file);
                        //if (Path.GetExtension(templateFile) == ".xls")
                        //    workbook = new HSSFWorkbook(file);
                        //else if (Path.GetExtension(templateFile) == ".xlsx")
                        //    workbook = new XSSFWorkbook(file);
                    }
                    ISheet sheet = workbook.GetSheetAt(0);
                    if (sheet != null && source != null && source.Rows.Count > 0)
                    {
                        IRow row; ICell cell;
                        //获取需插入数据的首行样式
                        IRow styleRow = sheet.GetRow(rowIndex);
                        if (styleRow == null)
                        {
                            for (int i = 0, len = source.Rows.Count; i < len; i++)
                            {
                                row = sheet.CreateRow(rowIndex);
                                //创建列并插入数据
                                for (int index = 0; index < cellCount; index++)
                                {
                                    row.CreateCell(index)
                                        .SetCellValue(!(source.Rows[i][cellKes[index]] is DBNull) ? source.Rows[i][cellKes[index]].ToString() : string.Empty);
                                }
                                rowIndex++;
                            }
                        }
                        else
                        {
                            for (int i = 0, len = source.Rows.Count; i < len; i++)
                            {
                                row = sheet.CreateRow(rowIndex);
                                row.HeightInPoints = styleRow.HeightInPoints;
                                row.Height = styleRow.Height;
                                //创建列并插入数据
                                for (int index = 0; index < cellCount; index++)
                                {
                                    var tx = source.Rows[i][cellKes[index]];
                                    var tc = styleRow.GetCell(index).CellType;
    
                                    cell = row.CreateCell(index, styleRow.GetCell(index).CellType);
                                    cell.CellStyle = styleRow.GetCell(index).CellStyle;
                                    cell.SetCellValue(!(source.Rows[i][cellKes[index]] is DBNull) ? source.Rows[i][cellKes[index]].ToString() : string.Empty);
                                }
                                rowIndex++;
                            }
                        }
                    }
                    return NPOIExport(strFileName + "." + templateFile.Split('.')[templateFile.Split('.').Length - 1], workbook);
                }
                catch (Exception ex)
                {
                    return ex.Message;
                }
    
            }
    
    
                    public static string NPOIExport(string fileName, IWorkbook workbook)
            {
                try
                {
                    System.IO.MemoryStream ms = new System.IO.MemoryStream();
                    workbook.Write(ms);
    
                    HttpContext.Current.Response.Clear();
                    HttpContext.Current.Response.ClearHeaders();
                    HttpContext.Current.Response.Cache.SetCacheability(System.Web.HttpCacheability.Private);
                    HttpContext.Current.Response.Buffer = true;
                    HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
                    HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", fileName));
                    HttpContext.Current.Response.ContentType = "application/ms-excel";
                    HttpContext.Current.Response.BinaryWrite(ms.ToArray());
                    HttpContext.Current.Response.Flush();
                    HttpContext.Current.Response.End();
                    ms.Close();
                    ms.Dispose();
                    return "导出成功";
                }
                catch (Exception ex)
                {
                    return "导出失败";
                }
            }
    View Code

     

    另外,需要引用的using也一同贴图

    using Aspose.Words;
    using NPOI.HSSF.UserModel;
    using NPOI.SS.UserModel;
    using NPOI.XSSF.UserModel;
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Data;
    using System.IO;
    using System.Linq;
    using System.Reflection;
    using System.Text.RegularExpressions;
    using System.Web;

     

    4】关于换行符

    此处 如果   Environment.NewLine 、<br/>   \n  无效,则建议使用下列换行符 ,但先必须引用 using Aspose.Words;

    using Aspose.Words;

    换行符:ControlChar.LineBreak 

     

    列:string ts="测试1"+ControlChar.LineBreak +"测试2";

    转载于:https://www.cnblogs.com/1439107348s/p/10637355.html

    展开全文
  • 利用占位符替换word中的字符串和添加图片 ///<summary> /// 替换word模板文件内容,包括表格中内容 /// 调用如下:WordStringsReplace("D:/CNSI/CNSI_1.doc", new ArrayList() { "old1", "old2" }, new...
    利用占位符替换word中的字符串和添加图片
      /// <summary>
            /// 替换word模板文件内容,包括表格中内容
            /// 调用如下:WordStringsReplace("D:/CNSI/CNSI_1.doc", new ArrayList() { "old1", "old2" }, new ArrayList() { "new1", "new2" });
            /// </summary>
            /// <param name="filePath"> 文件全路径 </param>
            /// <param name="arr_Old"> 占位符数组 </param>
            /// <param name="arr_New"> 替换字符串数组 </param>
            public void WordStringsReplace( string filePath, ArrayList arr_Old, ArrayList arr_New)
            {
                if (! File .Exists(filePath))
                {
                    MessageBox .Show( "模板文件不存在!" );
                    return ;
                }
                if (arr_Old.Count != arr_New.Count)
                {
                    MessageBox .Show( "占位符和替换内容不一致!" );
                    return ;
                }
                Microsoft.Office.Interop.Word. Application app = new Microsoft.Office.Interop.Word. Application ();
                object oMissing = System.Reflection. Missing .Value;
                object file = filePath;
                Microsoft.Office.Interop.Word. _Document doc = app.Documents.Open( ref file,
                       ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                       ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                       ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
                for ( int i = 0; i < arr_Old.Count; i++)
                {
                    app.Selection.Find.ClearFormatting();
                    app.Selection.Find.Replacement.ClearFormatting();
                    app.Selection.Find.Text = arr_Old[i].ToString();
                    app.Selection.Find.Replacement.Text = arr_New[i].ToString();
                    object objReplace = Microsoft.Office.Interop.Word. WdReplace .wdReplaceAll;
                    app.Selection.Find.Execute( ref oMissing, ref oMissing, ref oMissing,
                                               ref oMissing, ref oMissing, ref oMissing,
                                               ref oMissing, ref oMissing, ref oMissing,
                                               ref oMissing, ref objReplace, ref oMissing,
                                               ref oMissing, ref oMissing, ref oMissing);
                }
            
                //保存
                doc.Save();
                doc.Close( ref oMissing, ref oMissing, ref oMissing);
                app.Quit( ref oMissing, ref oMissing, ref oMissing);
            }
            /// <summary>
            /// 替换word模板文件中图片,这个只能替换一个图片,多个测试有点问题
            /// </summary>
            /// <param name="filePath"> 文件全路径 </param>
            /// <param name="str_Old"> 占位符字符串 </param>
            /// <param name="str_Pics"> 替换图片路径 </param>
            /// <param name="x"> x点位置,(0,0)在该占位符所在行和列的原点 </param>
            /// <param name="y"> y点位置 </param>
            /// <param name="width"> 图片宽度 </param>
            /// <param name="height"> 图片高度 </param>
            public void WordStringsReplace( string filePath, String str_Old, String str_Pics, int x, int y, int w, int h)
            {
                if (! File .Exists(filePath))
                {
                    MessageBox .Show( "模板文件不存在!" );
                    return ;
                }
                Microsoft.Office.Interop.Word. Application app = new Microsoft.Office.Interop.Word. Application ();
                object oMissing = System.Reflection. Missing .Value;
                object file = filePath;
                Microsoft.Office.Interop.Word. _Document doc = app.Documents.Open( ref file,
                       ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                       ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                       ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
                object replaceAll = Microsoft.Office.Interop.Word. WdReplace .wdReplaceAll;
                object LinkToFile = false ;
                object SaveWithDocument = true ;
                app.Selection.Find.ClearFormatting();
                app.Selection.Find.Text = str_Old;
                app.Selection.Find.Execute( ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
                object Anchor = app.Selection.Range;
                //oDoc.InlineShapes.AddPicture(picfileName, ref LinkToFile, ref SaveWithDocument, ref Anchor);         
                object left = x;
                object top = y;
                object width = w;
                object height = h;
                Anchor = app.Selection.Range;
                doc.Shapes.AddPicture(str_Pics, ref LinkToFile, ref SaveWithDocument, ref left, ref top, ref width, ref height, ref   Anchor);
                //保存
                doc.Save();
                doc.Close( ref oMissing, ref oMissing, ref oMissing);
                app.Quit( ref oMissing, ref oMissing, ref oMissing);
                //清除占位符
                WordStringsReplace( "D:/CNSI/CNSI_1.doc" , new ArrayList () { str_Old }, new ArrayList () { " " });
            }

    转载于:https://www.cnblogs.com/yanjinliang/p/5972041.html

    展开全文
  • 做一个demo,解析docx的word文档,替换占位符,并导出成pdf 分两步,第一步是解析word替换占位符,生成一个新的word文件。第二步再导出成pdf Springboot:2.4.0 一、解析word替换占位符 1.所需要的依赖: <!-...
  • 模板中的占位符替换问题

    千次阅读 2018-03-13 16:58:19
    现在很多开发者都会调用调用人家的接口,使用人家的模板,根据别人提供的参数,我们自动填充模板上的占位符。最近我在也占位符匹配问题,所以现在分享给大家它的具体实现过程。 比如我们有个模板如下:你好:{{0}},...
  • 1.占位符替换模板导出(只适用于word中含有表格形式的): /// <summary> /// 使用替换模板进行到处word文件 /// </summary> public class WordUtility { private object tempFile = null;...
  • 行数据会分为多个文本)的替换,针对占位符没有在同一个文本或者换行了都没有实现,总结docx4j和poi两种方式终极实现占位符替换生成新word,两种方式源码如下 1、Docx4J实现代码 import ...
  • 以前写过用asposeword 替换文字和图片,但是后来遇到问题,有些word替换替换图片后会导致打开时弹出错误:此文件中检测到错误,单word可以通过进行一下修复来打开文件。 考虑可能是版本有bug,于是从官网下了最新的...
  • libreOffice 官网 https://zh-cn.libreoffice.org/ 参考原文:... 安装 将下载的LibreOffice_6.1.3_Linux_x86-64_rpm.tar.gz的压缩包上传到linux中, tar -zxvf LibreOffi...
  • } } 3、进行占位符替换的操作 public class XWPFHelper { /** * 替换段落里面的变量 * @param doc 要替换的文档 * @param params 参数 */ public void replaceInPara(XWPFDocument doc, Map, Object> params) { for...
  • 注释掉里面的替换操作,就是把以上代码改为下面的 ///import core ///commands 本地图片引导上传 ///commandsName WordImage ///commandsTitle 本地图片引导上传 ///commandsDialog dialogs\wordimage UE....
  • I have a PDF that contains placeholders like , i want to be able to read in the PDF and change the PDF placeholder values to text using iText.So read in PDF, use maybe a replaceString() method and cha...
  • doc类型的word用HWPFDocument类进行解析 docx类型的word用XWPFDocument类进行解析 /** * * @param srcPath word模板数据源路径 * @param destPath word导出路径 * @param map 关键字键值对映射 * @...
  • //将需要替换的内容翻到map中,如果word中使用的不是${}形式,map的可以也需要修改 Map map = new HashMap(); map.put("${甲方盖章}","急急急"); map.put("${乙方签名}","烦烦烦"); map.put("${工作岗位}","java...
  • 1.java处理word是个大大的坑,无论是poi还是Java2word 都不是尽善尽美。 2.poi只能进行简单读操作,Java2word需要调用系统的com接口,系统机必须安装office和动态链接库。 3.word从2003版本就可以保存为xml格式,...
  • java替换占位符

    千次阅读 2019-01-08 17:42:38
    场景:替换{0}成我们想要的参数 方法一:用MessageFormat.format()方法。 public class zhanWeiFu{ public static void main(String[] args) { String str = "java{0}替换测试,{0}行不行,{0}可以的"; /*...
  • C语言中的占位符一般拼接一段字符串在编程中是很常见的事,下面简单做个总结: 什么是占位符?占位符就是先占住一个固定的位置,等着你再往里面添加内容的符号. 1.Java中处理方法: package com.amos; ...安卓编程资源...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 6,887
精华内容 2,754
关键字:

word占位符替换