当前位置: 首页 > article >正文

JAVA实现Word(doc)文件读写

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();
    }
}

最后,感谢王总的鼎力支持,谢谢!(2024年9月26日)


http://www.kler.cn/a/321479.html

相关文章:

  • Centos下的OpenSSH服务器和客户端
  • Kafka可视化工具 Offset Explorer (以前叫Kafka Tool)
  • 谈谈JSON
  • 三.统一异常Exception拦截处理
  • Windows开启IIS后依然出现http error 503.the service is unavailable
  • jsp | servlet | spring forEach读取不了对象List
  • 数学符号练习篇-函数
  • 云手机群控怎么用?有什么优势?
  • C语言 | Leetcode C语言题解之第438题找到字符串中所有字母异位词
  • AI 驱动旅游创业新机遇,旅游卡与共享旅游的融合发展
  • 微服务-流量染色
  • 【Gitee自动化测试2】Git,Github,Gitlab,Gitee
  • Java抽象教程!(* ̄;( ̄ *)
  • SQL 查询优化与实战
  • Laravel部署后,CPU 使用率过高
  • 为什么不用tensorflow而用opencv
  • 企微群管理软件:构建高效社群运营的新引擎
  • C 标准库 - <ctype.h>
  • 实战OpenCV之色彩空间转换
  • 第一个maven web工程(eclipse)
  • 【UE5】将2D切片图渲染为体积纹理,最终实现使用RT实时绘制体积纹理【第三篇-着色器光照】
  • 代码随想录打卡Day39
  • 【devops】devops-ansible模块介绍
  • 卷积神经网络-迁移学习
  • Spire.PDF for .NET【页面设置】演示:对PDF 文件进行分页
  • 【ASE】第一课_双面着色器