【Java】Apache poi对word文档进行写入操作

 最近在做一个自动生成Word文档的东西,需求是基于固定格式的doc文件,对其进行修改后生成一个新的doc文件(修改方法为替换)。

由于poi只提供了简单的读写操作,不支持样式,因此只能先事先准备好带有格式的doc文件。

poi下载地址:http://poi.apache.org/download.html

目前(2021年4月11日)最新版本是5.0.0

效果图
package com.company;
import java.io.*;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.*;
import org.apache.poi.hwpf.usermodel.Range;

public class WordReading {
    WordExtractor wordExtractor;
    public static void main(String[] args) {
        new WordReading().writeWord("D:\\模板.doc");
    }

    //写入word
    public void writeWord(String path){
        File file = new File(path);
        try{
            InputStream is = new FileInputStream(file);
            HWPFDocument doc = new HWPFDocument(is);
            //getRange方法读取doc文档全部内容
            Range range = doc.getRange();
            //替换文档内容
            range.replaceText("${标题}","阿里巴巴发布公开信");
            //输出到具体文件,如果doc文件不存在则自动生成
            OutputStream os = new FileOutputStream("D:\\生成文件.doc");
            doc.write(os);
            os.close();
        }catch (IOException e){
            e.printStackTrace();
        }
    }
}

 

要在Apache POI中给Word文档写入Wingdings字体的单选框,你可以使用XWPFRun的setFontFamily方法来设置字体,然后插入特定的字符来表示单选框。下面是一个示例代码: ```java import org.apache.poi.xwpf.usermodel.*; import java.io.FileOutputStream; import java.io.IOException; public class WordWingdingsCheckboxWriter { public static void main(String[] args) { // 创建一个新的空白文档 XWPFDocument document = new XWPFDocument(); // 创建一个段落 XWPFParagraph paragraph = document.createParagraph(); // 创建一个run XWPFRun run = paragraph.createRun(); // 设置字体为Wingdings run.setFontFamily("Wingdings"); // 插入单选框字符 run.setText("\uF0A7"); // 保存文档 try (FileOutputStream out = new FileOutputStream("wingdings_checkbox_example.docx")) { document.write(out); System.out.println("Wingdings单选框已成功写入到文档中!"); } catch (IOException e) { e.printStackTrace(); } } } ``` 在示例代码中,我们创建了一个空白的Word文档,并在其中添加了一个段落。然后,我们创建了一个`XWPFRun`对象,并使用`setFontFamily()`方法将字体设置为"Wingdings"。接下来,我们使用`setText()`方法插入了Wingdings字体中表示单选框的字符"\uF0A7"。最后,我们将文档保存为"wingdings_checkbox_example.docx"。 请注意,Wingdings字体中的特殊字符可以表示不同的符号,"\uF0A7"表示的是Wingdings字体中的一个单选框。你可以根据需要选择适合的字符来表示单选框。同时,在运行代码之前确保你已经引入了Apache POI的依赖。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Cimoon_

一分也是爱,用钱砸我

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值