1、pom.xml依赖

<dependencies>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-scratchpad</artifactId>
            <version>3.17</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

2、读取文件类ReadDoc.java

import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.*;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;

public class ReadDoc {
    public void testReadByDoc(String path) throws Exception {
        InputStream is = new FileInputStream(path);
        HWPFDocument doc = new HWPFDocument(is);
        //输出书签信息
        this.printInfo(doc.getBookmarks());
        //输出文本
        System.out.println(doc.getDocumentText());
        Range range = doc.getRange();
        this.printInfo(range);
        //读表格
        this.readTable(range);
        //读列表
        this.readList(range);
        //把当前HWPFDocument写到输出流中
        doc.write(new FileOutputStream("D:\\test.doc"));
        is.close();
    }

    /**
     * 输出书签信息
     * @param bookmarks
     */
    private void printInfo(Bookmarks bookmarks) {
        int count = bookmarks.getBookmarksCount();
        System.out.println("书签数量:" + count);
        Bookmark bookmark;
        for (int i=0; i<count; i++) {
            bookmark = bookmarks.getBookmark(i);
            System.out.println("书签" + (i+1) + "的名称是:" + bookmark.getName());
            System.out.println("开始位置:" + bookmark.getStart());
            System.out.println("结束位置:" + bookmark.getEnd());
        }
    }

    /**
     * 读表格
     * 每一个回车符代表一个段落,所以对于表格而言,每一个单元格至少包含一个段落,每行结束都是一个段落。
     * @param range
     */
    private void readTable(Range range) {
        //遍历range范围内的table。
        TableIterator tableIter = new TableIterator(range);
        Table table;
        TableRow row;
        TableCell cell;
        while (tableIter.hasNext()) {
            table = tableIter.next();
            int rowNum = table.numRows();
            for (int j=0; j<rowNum; j++) {
                row = table.getRow(j);
                int cellNum = row.numCells();
                for (int k=0; k<cellNum; k++) {
                    cell = row.getCell(k);
                    //输出单元格的文本
                    System.out.println(cell.text().trim());
                }
            }
        }
    }

    /**
     * 读列表
     * @param range
     */
    private void readList(Range range) {
        int num = range.numParagraphs();
        Paragraph para;
        for (int i=0; i<num; i++) {
            para = range.getParagraph(i);
            if (para.isInList()) {
                System.out.println("list: " + para.text());
            }
        }
    }

    /**
     * 输出Range
     * @param range
     */
    private void printInfo(Range range) {
        //获取段落数
        int paraNum = range.numParagraphs();
        System.out.println(paraNum);
        for (int i=0; i<paraNum; i++) {
            System.out.println("段落" + (i+1) + ":" + range.getParagraph(i).text());
        }
        int secNum = range.numSections();
        System.out.println(secNum);
        Section section;
        for (int i=0; i<secNum; i++) {
            section = range.getSection(i);
            System.out.println(section.getMarginLeft());
            System.out.println(section.getMarginRight());
            System.out.println(section.getMarginTop());
            System.out.println(section.getMarginBottom());
            System.out.println(section.getPageHeight());
            System.out.println(section.text());
        }
    }
}

3、功能测试

public class ReadDocTest {

    public static void main(String[] args) throws Exception {
        ReadDoc rd = new ReadDoc();
        rd.testReadByDoc("D:\\MaintainCase.doc");
    }

}

4、写入文件类WriteDoc.java

import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Range;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

public class WriteDoc {
    public void testWrite() throws Exception {
        List<Users> list = new ArrayList<Users>();
        list.add(new Users("a","男",10,new SimpleDateFormat("yyyy-MM-dd").parse("2018-08-08")));
        list.add(new Users("b","女",20,new SimpleDateFormat("yyyy-MM-dd").parse("2017-07-07")));

        String templatePath = "D:\\template.doc";
        InputStream is = new FileInputStream(templatePath);
        OutputStream os = null;
        HWPFDocument doc = new HWPFDocument(is);
        Range range = doc.getRange();
        for(int i=0;i<list.size();i++){
            Users user = list.get(i);
            //把range范围内的${reportDate}替换为当前的日期
            range.replaceText("${name}", user.getName());
            range.replaceText("${sex}", user.getSex());
            range.replaceText("${age}", String.valueOf(user.getAge()));
            range.replaceText("${date}", user.getBirthday().toString());
            os = new FileOutputStream(new File("D:\\"+user.getName()+".doc"));
            //把doc输出到输出流中
            doc.write(os);
        }
        os.close();
        is.close();
    }
}

5、功能测试

Users类

import java.util.Date;

public class Users {

    String name;
    String sex;
    int age;
    Date birthday;

    public Users() {}

    public Users(String name, String sex ,int age, Date birthday) {
        this.name = name;
        this.sex = sex;
        this.age = age;
        this.birthday = birthday;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

6、测试类

public class WriteDocTest {

    public static void main(String[] args) throws Exception {
        WriteDoc wd = new WriteDoc();
        wd.testWrite();
    }
}

JAVA实现Word(doc)文件读写的更多相关文章

  1. 使用POI读写Word doc文件

    使用POI读写word doc文件 目录 1     读word doc文件 1.1     通过WordExtractor读文件 1.2     通过HWPFDocument读文件 2     写w ...

  2. android使用POI读写word doc文件

    目录 1     读word doc文件 1.1     通过WordExtractor读文件 1.2     通过HWPFDocument读文件 2     写word doc文件 Apache p ...

  3. Java 字符流实现文件读写操作(FileReader-FileWriter)

    Java 字符流实现文件读写操作(FileReader-FileWriter) 备注:字符流效率高,但是没有字节流底层 字节流地址:http://pengyan5945.iteye.com/blog/ ...

  4. 使用POI转换word doc文件

    目录 1       转换为Html文件 2       转换为Xml文件 3       转换为Text文件 在POI中还存在有针对于word doc文件进行格式转换的功能.我们可以将word的内容 ...

  5. POI转换word doc文件为(html,xml,txt)

    在POI中还存在有针对于word doc文件进行格式转换的功能.我们可以将word的内容转换为对应的Html文件,也可以把它转换为底层用来描述doc文档的xml文件,还可以把它转换为底层用来描述doc ...

  6. VBA/VBScript提取Word(*.doc)文件中包含的图片(照片)

    VBA/VBScript提取Word(*.doc)文件中包含的图片(照片)   要处理的人事简历表是典型的Word文档,其中一人一份doc,里面包含有个人的照片,如果要把里面的照片复制出来就比较麻烦了 ...

  7. 【java学习笔记】文件读写(IO流)

    1.字节流 FileInputStream.FileOutputStream ①FileInputStream import java.io.FileInputStream; public class ...

  8. JAVA实现word doc docx pdf excel的在线浏览 - 仿百度文库 源码

    我们具体实现思路是这样的 首先下载并安装openoffice和swftools openoffice下载地址:http://www.openoffice.org/download/index.html ...

  9. java中的File文件读写操作

    之前有好几次碰到文件操作方面的问题,大都由于时间太赶而没有好好花时间去细致的研究研究.每次都是在百度或者博客或者论坛里面參照着大牛们写的步骤照搬过来,之后再次碰到又忘记了.刚好今天比較清闲.于是就在网 ...

  10. POI把html写入word doc文件

    直接把Html文本写入到Word文件 获取查看页面的body内容和引用的css文件路径传入到后台. 把对应css文件的内容读取出来. 利用body内容和css文件的内容组成一个标准格式的Html文本. ...

随机推荐

  1. 性能测试四十九:ngrinder压测平台

    下载地址:https://sourceforge.net/projects/ngrinder/files/ ngrinder工作原理:这里的controller就是ngrinder平台 部署(以win ...

  2. 常用的web服务器软件整理

    (1)ApacheApache是世界使用排名第一的Web服务器软件.它可以运行在几乎所有广泛使用的计算机平台上.Apache源于NCSAhttpd服务器,经过多次修改,成为世界上最流行的Web服务器软 ...

  3. gitlab报错502及处理

    报错截图: 解决: 1.端口问题 如上面写的815端口,那配置文件的8080端口都改成815端口 之后重新载入配置文件,并开启 gitlab-ctl reconfigure gitlab-ctl st ...

  4. 饮冰三年-人工智能-linux-06 系统启动流程及安全

    系统启动流程 BOIS(Basic Input/Output System)基本输入输出系统:硬件和软件之间的接口,而且是很基本的接口. grub(Grand Unified BootLoader)多 ...

  5. Html列表分页算法

    public class PageHelper { /// <summary> /// 标签 /// </summary> public string Tag { get; s ...

  6. 解决AS gradle下载同步卡慢的问题

    国内因为GFW的原因,导致同步谷歌等服务器的插件源非常非常慢,几乎是龟爬,还好有阿里云的镜像源,据说速度很快,还不快试试: 1.build.gradle里的buildscript和allproject ...

  7. Visual Studio 中使用万能头文件 #include <bits/stdc++.h>

    最近开始使用VS,之前用的DEV C++软件可直接使用 #include <bits/stdc++.h>  ,但VS中并没有,为了使用方便,可直接在VS中添加此头文件,方法如下: 1.在安 ...

  8. python函数式编程——返回函数

    1.函数作为返回值 高阶函数除了可以接受函数作为参数外,还可以把函数作为结果值返回. 2.闭包 注意到返回的函数在其定义内部引用了局部变量args,所以,当一个函数返回了一个函数后,其内部的局部变量还 ...

  9. dos文件(夹)复制命令:copy和xcopy

    1.copy命令 将一份或多份文件复制到另一个位置. COPY [/D] [/V] [/N] [/Y | /-Y] [/Z] [/L] [/A | /B ] source [/A | /B] [+ s ...

  10. 51Nod1634 刚体图 动态规划 容斥原理 排列组合

    原文链接https://www.cnblogs.com/zhouzhendong/p/51Nod1634.html 题目传送门 - 51Nod1634 题意 基准时间限制:1 秒 空间限制:13107 ...