当前位置: 首页 > 知识库问答 >
问题:

Apache POI Word教程。

昝涛
2023-03-14

有人知道关于使用Apache POI库使用MS Word的好教程吗?我想了解如何创建word documents.doc(或者我可能需要创建template.dot),以便在文档(模板)中创建诸如${customer.name}之类的变量,然后通过range.replaceText(“${customer.name}”,“Microsoft Co”)替换它;或者${customer.name}不是变量,只是纯文本(为了更清楚起见,将其命名为变量名)?另外,我也没有在POI中找到关于使用表的教程

事实上,我有一个。doc文档,我需要替换一些变量,比如Name、nushe,还需要用一些值填充表。

共有1个答案

璩华辉
2023-03-14

您可以使用Microsoft Word在Word文档中使用书签。我一周前就做过了。我通过选择要替换的文本在文档中插入书签,然后插入->bookmark并键入一个新的书签名称。之后,在代码中,您应该在util类中实现如下内容:

/** 
 * Inserts a value at a location within the Word document specified by a 
 * named bookmark. 
 * 
 * @param bookmarkName An instance of the String class that encapsulates 
 *        the name of the bookmark. Note that case is important and the case 
 *        of the bookmarks name within the document and that of the value 
 *        passed to this parameter must match. 
 * @param bookmarkValue An instance of the String class that encapsulates 
 *        the value that should be inserted into the document at the location 
 *        specified by the bookmark. 
 */ 
public final void insertAtBookmark(String bookmarkName, String bookmarkValue, Style style) { 
    List<XWPFTable> tableList = null; 
    Iterator<XWPFTable> tableIter = null; 
    List<XWPFTableRow> rowList = null; 
    Iterator<XWPFTableRow> rowIter = null; 
    List<XWPFTableCell> cellList = null; 
    Iterator<XWPFTableCell> cellIter = null; 
    XWPFTable table = null; 
    XWPFTableRow row = null; 
    XWPFTableCell cell = null; 

    // Firstly, deal with any paragraphs in the body of the document. 
    this.procParaList(this.document.getParagraphs(), bookmarkName, bookmarkValue, style); 

    // Then check to see if there are any bookmarks in table cells. To do this 
    // it is necessary to get at the list of paragraphs 'stored' within the 
    // individual table cell, hence this code which get the tables from the 
    // document, the rows from each table, the cells from each row and the 
    // paragraphs from each cell. 
    tableList = this.document.getTables(); 
    tableIter = tableList.iterator(); 
    while(tableIter.hasNext()) { 
        table = tableIter.next(); 
        rowList = table.getRows(); 
        rowIter = rowList.iterator(); 
        while(rowIter.hasNext()) { 
            row = rowIter.next(); 
            cellList = row.getTableCells(); 
            cellIter = cellList.iterator(); 
            while(cellIter.hasNext()) { 
                cell = cellIter.next(); 
                this.procParaList(cell.getParagraphs(), 
                        bookmarkName, 
                        bookmarkValue, style); 
            } 
        } 
    } 
}

/** 
 * Inserts text into the document at the position indicated by a specific 
 * bookmark. Note that the current implementation does not take account 
 * of nested bookmarks, that is bookmarks that contain other bookmarks. Note 
 * also that any text contained within the bookmark itself will be removed. 
 * 
 * @param paraList An instance of a class that implements the List interface 
 *        and which encapsulates references to one or more instances of the 
 *        XWPFParagraph class. 
 * @param bookmarkName An instance of the String class that encapsulates the 
 *        name of the bookmark that identifies the position within the 
 *        document some text should be inserted. 
 * @param bookmarkValue An instance of the AString class that encapsulates 
 *        the text that should be inserted at the location specified by the 
 *        bookmark. 
 */ 
private final void procParaList(List<XWPFParagraph> paraList, 
        String bookmarkName, String bookmarkValue,Style style) { 
    Iterator<XWPFParagraph> paraIter = null; 
    XWPFParagraph para = null; 
    List<CTBookmark> bookmarkList = null; 
    Iterator<CTBookmark> bookmarkIter = null; 
    CTBookmark bookmark = null; 
    XWPFRun run = null; 
    Node nextNode = null; 

    // Get an Iterator to step through the contents of the paragraph list. 
    paraIter = paraList.iterator(); 
    while(paraIter.hasNext()) { 
        // Get the paragraph, a llist of CTBookmark objects and an Iterator 
        // to step through the list of CTBookmarks. 
        para = paraIter.next(); 
        bookmarkList = para.getCTP().getBookmarkStartList(); 
        bookmarkIter = bookmarkList.iterator(); 

        while(bookmarkIter.hasNext()) { 
            // Get a Bookmark and check it's name. If the name of the 
            // bookmark matches the name the user has specified... 
            bookmark = bookmarkIter.next(); 
            if(bookmark.getName().equals(bookmarkName)) { 
                // ...create the text run to insert and set it's text 
                // content and then insert that text into the document. 
                run = para.createRun(); 
                run.setText(bookmarkValue); 
                //run.set
                /*CTR ctr = run.getCTR(); 
                CTRPr ctrPr = ctr.getRPr(); 

                if(ctrPr == null) { 
                    ctrPr = ctr.addNewRPr(); 
                } */
                if(defaultStyle != null || style != null){
                //ctrPr.addNewRFonts().setAscii("Calibri");
                    if(style != null){
                        applyStyleToRun(style, run);
                        if(style.isCenter()) para.setAlignment(ParagraphAlignment.CENTER);
                    }else{
                        if(defaultStyle.isCenter()) para.setAlignment(ParagraphAlignment.CENTER);
                        applyStyleToRun(defaultStyle, run);
                    }

                }

                // The new Run should be inserted between the bookmarkStart 
                // and bookmarkEnd nodes, so find the bookmarkEnd node. 
                // Note that we are looking for the next sibling of the 
                // bookmarkStart node as it does not contain any child nodes 
                // as far as I am aware. 
                nextNode = bookmark.getDomNode().getNextSibling(); 
                // If the next node is not the bookmarkEnd node, then step 
                // along the sibling nodes, until the bookmarkEnd node 
                // is found. As the code is here, it will remove anything 
                // it finds between the start and end nodes. This, of course 
                // comepltely sidesteps the issues surrounding boorkamrks 
                // that contain other bookmarks which I understand can happen. 
                while(nextNode != null &&  nextNode.getNodeName() != null &&  !(nextNode.getNodeName().contains("bookmarkEnd"))) { 
                    para.getCTP().getDomNode().removeChild(nextNode); 
                    nextNode = bookmark.getDomNode().getNextSibling(); 
                } 

                // Finally, insert the new Run node into the document 
                // between the bookmarkStrat and the bookmarkEnd nodes. 
                para.getCTP().getDomNode().insertBefore( 
                        run.getCTR().getDomNode(), 
                        nextNode); 
            } 
        } 
    } 
}

/**
 * Applique un style sur un XWPFRun 
 * @param style
 * @param run
 */
private void applyStyleToRun(Style style, XWPFRun run) {
    run.setFontSize(style.getFontSize());
    if(style.getFontFamily() != null){
        run.setFontFamily(style.getFontFamily());
    }
    run.setBold(style.isBold());
    run.setItalic(style.isItalic());
    if(style.getColorCode() != null){
        run.getCTR().addNewRPr().addNewColor().setVal(style.getColorCode());
    }

} 

在这里找到的原始代码:http://apache-poi.1045710.n5.nabble.com/replacing-the-value-of-the-bookmarks-td5710052.html

 类似资料:
  • 原文:Pyplot tutorial matplotlib.pyplot是一个命令风格函数的集合,使matplotlib的机制更像 MATLAB。 每个绘图函数对图形进行一些更改:例如,创建图形,在图形中创建绘图区域,在绘图区域绘制一些线条,使用标签装饰绘图等。在matplotlib.pyplot中,各种状态跨函数调用保存,以便跟踪诸如当前图形和绘图区域之类的东西,并且绘图函数始终指向当前轴域(请

  • 原文:Path Tutorial 位于所有matplotlib.patch对象底层的对象是Path,它支持moveto,lineto,curveto命令的标准几个,来绘制由线段和样条组成的简单和复合轮廓。 路径由(x,y)顶点的(N,2)数组,以及路径代码的长度为 N 的数组实例化。 例如,为了绘制(0,0)到(1,1)的单位矩形,我们可以使用这个代码: import matplotlib.pyp

  • 原文:Transformations Tutorial 像任何图形包一样,matplotlib 建立在变换框架之上,以便在坐标系,用户数据坐标系,轴域坐标系,图形坐标系和显示坐标系之间轻易变换。 在 95 %的绘图中,你不需要考虑这一点,因为它发生在背后,但随着你接近自定义图形生成的极限,它有助于理解这些对象,以便可以重用 matplotlib 提供给你的现有变换,或者创建自己的变换(见matpl

  • 原文:Image tutorial 启动命令 首先,让我们启动 IPython。 它是 Python 标准提示符的最好的改进,它与 Matplotlib 配合得相当不错。 在 shell 或 IPython Notebook 上都可以启动 IPython。 随着 IPython 启动,我们现在需要连接到 GUI 事件循环。 它告诉 IPython 在哪里(以及如何显示)绘图。 要连接到 GUI 循

  • 原文:Artist tutorial matplotlib API 有三个层级。 matplotlib.backend_bases.FigureCanvas是绘制图形的区域,matplotlib.backend_bases.Renderer是知道如何在ChartCanvas上绘制的对象,而matplotlib.artist.Artist是知道如何使用渲染器在画布上画图的对象。 FigureCanv

  • Movie 网站 (类似于IMDB) 多租户系统

  • 接下来的教程讲先介绍Gradle的基础知识 Chapter 4, 安装 Gradle 描述如何安装 Gradle. Chapter 5, 脚本构建基础 介绍脚本构建的基础元素: projects 和 tasks. Chapter 6, Java 快速入门 展示如何使用 Gradle 来构建 Java 项目. Chapter 7, 依赖管理基础 展示如何使用 Gradle 的依赖管理功能. Chap

  • 链接 地面站 编写应用程序 QGC的视频流 远距离视频流 u-blox M8P RTK 光流 ecl EKF 飞行前检查 着陆检测 Linux系统下使用S.Bus驱动