Java操作Word

本文介绍了如何使用Apache POI库进行Word文档的读写操作,包括导出和导入,并详细阐述了结合Freemarker模板生成Word文档的步骤,包括模板设计、依赖添加和代码实现。此外,还讨论了Freemarker模板的优缺点以及如何处理循环操作。
摘要由CSDN通过智能技术生成

Poi工具

Apache的POI,是Apache软件基金会的开放源码函式库,POI提供API给Java程序对Microsoft
Office格式档案读和写的功能。POI读写Excel功能强大、操作简单。但是POI操作时,一般只用它读取word文档,POI只能能够创建简单的word文档,相对而言POI操作时的功能太少。

添加Poi依赖

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.15</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml-schemas</artifactId>
    <version>3.15</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>3.15</version>
</dependency>

导出

1)导出语句如下

public void upload() throws IOException {
   
XWPFDocument doc = new XWPFDocument();// 创建Word文件
    XWPFParagraph p = doc.createParagraph();// 新建一个段落
    p.setAlignment(ParagraphAlignment.CENTER);// 设置段落的对齐方式
    p.setBorderBottom(Borders.DOUBLE);//设置下边框
    p.setBorderTop(Borders.DOUBLE);//设置上边框
    p.setBorderRight(Borders.DOUBLE);//设置右边框
    p.setBorderLeft(Borders.DOUBLE);//设置左边框
    XWPFRun r = p.createRun();//创建段落文本
    r.setText("POI创建的Word段落文本");
    r.setBold(true);//设置为粗体
    r.setColor("FF0000");//设置颜色
    p = doc.createParagraph();// 新建一个段落
    r = p.createRun();
    r.setText("POI读写Excel功能强大、操作简单。");
    XWPFTable table= doc.createTable(3, 3);//创建一个表格
    table.getRow(0).getCell(0).setText("表格1");
    table.getRow(1).getCell(1).setText("表格2");
    table.getRow(2).getCell(2).setText("表格3");
    FileOutputStream out = new FileOutputStream("D:\\记事本\\公司\\word\\sample.doc");
    doc.write(out);
    out.close();
}

2)调用接口。导出后的word如下。

导入

1)导入语句如下。

public void importWord(@RequestParam("file") MultipartFile file) throws IOException {
   
if (file == null) {
   
        System.out.println("文件不能为空");
    }
    // 创建Word文件
    XWPFDocument doc = new XWPFDocument(file.getInputStream());
    //遍历段落
    for (XWPFParagraph p : doc.getParagraphs())
    {
   
        System.out.println(p.getParagraphText
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值