整合营销服务商

电脑端+手机端+微信端=数据同步管理

免费咨询热线:

Java 用文本或表格替换Word书签内容

文将使用Free Spire.Doc for Java免费控件来演示如何替换Word文档中添加有书签的文本段落。具体内容如下:

  • 文本替换书签内容
  • 表格替换书签内容

在运行代码前,需将jar包导入IDEA。可通过下载产品包手动导入或在Maven下的pom.xml文件中添加如下引用。

<repositories>
        <repository>
            <id>com.e-iceblue</id>
            <url>http://repo.e-iceblue.cn/repository/maven-public/</url>
        </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.doc.free</artifactId>
        <version>3.9.0</version>
    </dependency>
</dependencies>

示例1 用文本替换书签内容

import com.spire.doc.*;
import com.spire.doc.documents.*;

public class ReplaceWithText {
    public static void main(String[] args) {
        //加载Word文档
        Document doc = new Document("C:\\Users\\Test1\\Desktop\\Sample.docx");

        //定位到书签"MyBookmark"
        BookmarksNavigator bookmarkNavigator = new BookmarksNavigator(doc);
        bookmarkNavigator.moveToBookmark("MyBookmark");

        //使用文本替换原书签的内容, false表示不保留原来的格式
        bookmarkNavigator.replaceBookmarkContent("使用文本替换书签内容", false);

        //保存文档
        doc.saveToFile("output/ReplaceWithText.docx", FileFormat.Docx);
    }
}

或使用Html String替换书签内容

import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.ParagraphBase;

public class ReplaceWithHTMLString {
    public static void main(String[] args) {
        //加载Word文档
        Document doc = new Document("C:\\Users\\Test1\\Desktop\\Sample.docx");

        //临时添加一个section
        Section tempSection = doc.addSection();
        //添加段落到section并添加Html string到段落
        String html = "使用文本替换书签内容";
        tempSection.addParagraph().appendHTML(html);

        //获取段落的第一项和最后一项
        ParagraphBase firstItem = (ParagraphBase)tempSection.getParagraphs().get(0).getItems().getFirstItem();
        ParagraphBase lastItem = (ParagraphBase)tempSection.getParagraphs().get(0).getItems().getLastItem();
        //创建TextBodySelection对象
        TextBodySelection selection = new TextBodySelection(firstItem, lastItem);
        //创建TextBodyPart对象
        TextBodyPart bodyPart = new TextBodyPart(selection);

        //定位到书签"MyBookmark"
        BookmarksNavigator bookmarkNavigator = new BookmarksNavigator(doc);
        bookmarkNavigator.moveToBookmark("MyBookmark");

        //使用Html string替换原书签的内容
        bookmarkNavigator.replaceBookmarkContent(bodyPart);

        //移除临时添加的section
        doc.getSections().remove(tempSection);

        //保存结果文档
        doc.saveToFile("output/ReplaceWithHTMLString.docx", FileFormat.Docx);
    }
}

替换前后对比:

示例2 用表格替换书签内容

import com.spire.doc.*;
import com.spire.doc.documents.*;

public class ReplaceWithTable {
    public static void main(String[] args) {
        //加载Word文档
        Document doc = new Document("C:\\Users\\Test1\\Desktop\\Sample.docx");

        String[][] data =
                {
                new String[]{"名称", "额定容量", "电源", "工作时间"},
                new String[]{"LED-901充电式手电筒", "900mAH", "AC110V/220V", "26个小时"},
                };

        //创建表格
        Table table = new Table(doc, true);
        table.resetCells(2, 4);
        for (int i = 0; i < data.length; i++) {
            TableRow dataRow = table.getRows().get(i);
            for (int j = 0; j < data[i].length; j++) {
                dataRow.getCells().get(j).addParagraph().appendText(data[i][j]);
            }
        }

        //创建TextBodyPart对象
        TextBodyPart bodyPart= new TextBodyPart(doc);
        bodyPart.getBodyItems().add(table);

        //定位到书签"MyBookmark"
        BookmarksNavigator bookmarkNavigator = new BookmarksNavigator(doc);
        bookmarkNavigator.moveToBookmark("MyBookmark");

        //使用表格替换原书签的内容
        bookmarkNavigator.replaceBookmarkContent(bodyPart);

        //保存文档
        doc.saveToFile("output/ReplaceWithTable.docx", FileFormat.Docx);
    }
}

替换效果:

推荐阅读:

如何添加、读取、删除Word书签

件传递有两种方式,冒泡和捕获。事件传递定义了元素事件触发的顺序,在冒泡中,内部元素的事件会先被触发,然后在触发外部元素,如先触发p元素然后触发div元素。在捕获事件中,外部元素先被触发,然后内部事件触发。addEventListener() 方法可以指定 "useCapture" 参数来设置传递类型:addEventListener(event, function, useCapture);

创建新的HTML元素(节点)appendChild()

HTML Collection与NodeList的区别:NodeList 与 HTMLCollection 有很多类似的地方。NodeList 与 HTMLCollection 都与数组对象有点类似,可以使用索引 (0, 1, 2, 3, 4, ...) 来获取元素。NodeList 与 HTMLCollection 都有 length 属性。节点列表不是一个数组!节点列表无法使用数组的方法: valueOf(), pop(), push(), 或 join() 。

页数据提取的方法很多,从其基本原理来说很多就是通过模拟http请求,发送给服务器,然后接收响应,解析响应的结果。整个过程说简单也简单,说复杂也复杂。这里来整理下做过的一些事,走过的路,遇到的坑。



1,基本思路


这里举一个java下载的例子,说明简单的思路。


public void downPDF(String urlString, String filename, String pdf,

String chk, String chk1, String chk2, String chk3) throws Exception {

URL server = new URL(urlString);

HttpURLConnection connection = (HttpURLConnection) server

.openConnection();

connection.setRequestMethod("GET");

connection.setDoInput(true);

connection.setDoOutput(true);

connection.setUseCaches(false);

connection.addRequestProperty("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");

connection.addRequestProperty("Accept-Language", "zh-cn,zh;q=0.5");

connection.addRequestProperty("Accept-Encoding", "gzip, deflate");

connection.addRequestProperty("Accept-Charset","GB2312,utf-8;q=0.7,*;q=0.7");

connection.addRequestProperty("Cookie","chk=");

connection.addRequestProperty("User-Agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; .NET CLR2.0.50727; MS-RTC LM 8)");

// if (headers != null) {

// for (Header h : headers) {

// System.out.println(h.getName() + ":" + h.getValue());

// connection.addRequestProperty(h.getName(), h.getValue());

// }

// }

connection.connect();

InputStream is = connection.getInputStream();

OutputStream os = new FileOutputStream(filename);

byte[] buffer = new byte[1024 * 128];


if (true) {

int byteReaded = is.read(buffer);

while (byteReaded != -1) {

os.write(buffer, 0, byteReaded);

byteReaded = is.read(buffer);

}