apache poi 读写word

word 后缀有doc、docx。今天只写了docx的。写的不好,大家多指教

maven管理,pom文件添加了依赖

<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>4.1.2</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml-schemas -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml-schemas</artifactId>
    <version>4.1.2</version>
</dependency>

文件内容:乱敲的

1.读取本地文件word文档,获取内容,代码如下:
@Test
public void read(){
    FileInputStream is = null;
    XWPFDocument xwpfDocument = null;
    try {
        is = new FileInputStream("D:\\uploads\\test.docx");
        xwpfDocument = new XWPFDocument(is);
        XWPFWordExtractor xwpfWordExtractor = new XWPFWordExtractor(xwpfDocument);
        String text = xwpfWordExtractor.getText();
        System.out.println(text);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

效果:

 2.在本地新建word,写入内容

@Test
public void write1(){
    //创建word文件
    XWPFDocument document = new XWPFDocument();
    FileOutputStream os = null;
    try {
        os = new FileOutputStream("d://uploads//2.docx");
        //创建个段落
        XWPFParagraph paragraph = document.createParagraph();
        XWPFRun run = paragraph.createRun();
        //写入内容
        run.setText("HELLO!我是一个中国人,我爱我的祖国!");
        run.setBold(true);   
        run.setColor("ff0000");
        run.setItalic(true);

        //创建表格
        XWPFTable tab = document.createTable();
        tab.setWidth(5000); // 表格宽度
        //第一行
        XWPFTableRow row = tab.getRow(0);
        row.setHeight(1000); // 表格高度
        //创建列
        row.getCell(0).setText("Sl.No.");
        row.addNewTableCell().setText("Name");
        row.addNewTableCell().setText("Email");
        //第二行
        row = tab.createRow();
        row.getCell(0).setText("1.");
        row.getCell(1).setText("eric");
        row.getCell(2).setText("eric@gmail.com");
        //第三行
        row = tab.createRow();
        row.getCell(0).setText("2.");
        row.getCell(1).setText("jack");
        row.getCell(2).setText("jack@gmail.com");
        document.write(os);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        try {
            os.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

效果:

  • 21
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值