POI:对Word的基本操作

1 向word中写入文本并设置样式

package com.example;

import org.apache.poi.xwpf.usermodel.*;

import java.io.File;
import java.io.FileOutputStream;

/**
 * @Author:xiexu
 * @Date:2024/1/12 23:54
 */
public class WriteWord {
    static String PATH = "D:\\Idea-projects\\POI_word";
    public static void main(String[] args) throws Exception {
        // 1. 创建文档
        XWPFDocument document = new XWPFDocument();
        // 2. 创建一个标题段落
        XWPFParagraph titleParagraph = document.createParagraph();
        // 设置段落为居中
        titleParagraph.setAlignment(ParagraphAlignment.CENTER);
        // 3. 创建第一段的运行
        XWPFRun titleParagraphRun = titleParagraph.createRun();
        // 4. 设置文本
        titleParagraphRun.setText("这是一个标题");
        // 5. 设置第一个段落中文本样式
        titleParagraphRun.setFontSize(20);
        titleParagraphRun.setBold(true);
        titleParagraphRun.setFontFamily("宋体");
        titleParagraphRun.setColor("FF0000");



        // 6. 创建第二个段落
        XWPFParagraph contentParagraph = document.createParagraph();
        // 设置段落为左对齐
        contentParagraph.setAlignment(ParagraphAlignment.LEFT);
        // 设置首行缩进
        contentParagraph.setIndentationFirstLine(400);
        contentParagraph.setBorderBottom(Borders.BASIC_BLACK_DASHES);  // 加边框(上右下左都可以)
        // 7. 创建第二段的运行
        XWPFRun contentParagraphRun = contentParagraph.createRun();
        // 8. 设置文本 (这边使用StringBuffer来拼接字符,来模拟文章效果)
        StringBuffer content = new StringBuffer();
        for (int i = 0; i < 50; i++) {
            content.append("小蟹学Java-POI");
        }
        contentParagraphRun.setText(content.toString());
        contentParagraphRun.setItalic(true);
        //twoParagraphRun.setStrike(true);  // 删除线
        // contentParagraphRun.setSubscript(VerticalAlign.SUBSCRIPT);  // 下标

        contentParagraphRun.addBreak();  // 添加个换行


        // 9. 创建第三个段落
        XWPFParagraph endParagraph = document.createParagraph();
        // 设置段落为右对齐
        endParagraph.setAlignment(ParagraphAlignment.RIGHT);
        // 10. 创建第三个段的运行
        XWPFRun endParagraphRun = endParagraph.createRun();
        // 11.设置文本
        endParagraphRun.setText("结束");
        endParagraphRun.setFontSize(16);
        endParagraphRun.setColor("8E0500");



        // 创建一个文件对象
        File file = new File(PATH + "\\write_word.docx");
        // 创建一个文件输出流
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        // 通过输出流,将目标文件写入到磁盘
        document.write(fileOutputStream);

        // 关闭输出流
        fileOutputStream.close();

        // 输出提示
        System.out.println("文件创建成功");

    }
}

POI:对Word的基本操作_第1张图片

 

2 创建基础的表格

package com.example;

import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.List;

/**
 * @Author:xiexu
 * @Date:2024/1/13 10:18
 */
public class WriteTable {
    static String PATH = "D:\\Idea-projects\\POI_word";
    public static void main(String[] args) throws Exception {
        XWPFDocument document = new XWPFDocument();

        // 创建表格
        XWPFTable table = document.createTable();

        // 创建第一行
        XWPFTableRow oneRow = table.getRow(0);
        oneRow.getCell(0).setText("col one, row one");
        oneRow.addNewTableCell().setText("col two, row one");
        oneRow.addNewTableCell().setText("col three, row one");

        // 创建第二行
        XWPFTableRow twoRow = table.createRow();
        twoRow.getCell(0).setText("col one, row two");
        twoRow.getCell(1).setText("col two, row two");
        twoRow.getCell(2).setText("col three, row two");

        // 创建第三行
        XWPFTableRow threeRow = table.createRow();
        threeRow.getCell(0).setText("col one, row three");
        threeRow.getCell(1).setText("col two, row three");
        threeRow.getCell(2).setText("col three, row three");


        File file = new File(PATH + "\\write_table.docx");

        FileOutputStream fileOutputStream = new FileOutputStream(file);

        document.write(fileOutputStream);

        fileOutputStream.close();

        System.out.println("表格写入成功!");
    }
}

POI:对Word的基本操作_第2张图片

 

3 给表格添加样式

 在这边的话,就不用上述的方法创建表格了,直接给出行数和列数也是可以直接创建表格的

package com.example;

import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;

import java.io.File;
import java.io.FileOutputStream;
import java.math.BigInteger;
import java.util.List;

/**
 * @Author:xiexu
 * @Date:2024/1/13 10:40
 */
public class SetTableStyle {
    static String PATH = "D:\\Idea-projects\\POI_word";
    public static void main(String[] args) throws Exception {
        // 1. 创建一个文档对象
        XWPFDocument document = new XWPFDocument();

        // 2. 给出行数和列数
        int RowNums = 5;
        int colNums = 6;

        // 3.  创建表格对象
        XWPFTable table = document.createTable(RowNums, colNums);

        // 4. 设置表格样式
        // 4.1 获取表格(table)的属性对象(CTTblPr),该对象用于描述表格的一些属性,例如样式、边框等
        CTTblPr tblPr = table.getCTTbl().getTblPr();
        // 4.2创建一个新的表格样式对象(CTString),并将其添加到表格属性对象中
        CTString tblStyle = tblPr.addNewTblStyle();
        // 4.3设置表格样式对象的值为 "TableStyle"
        tblStyle.setVal("TableStyle");


        // 4.4 获取所有的行并设置样式
        List rows = table.getRows();

        int currentRow = 0;
        int currentCol = 0;

        for (XWPFTableRow row : rows) {
            // 设置行高
            CTTrPr ctTrPr = row.getCtRow().addNewTrPr();
            CTHeight ctHeight = ctTrPr.addNewTrHeight();
            ctHeight.setVal(BigInteger.valueOf(300));

            // 设置单元格样式
            List cells = row.getTableCells();
            for (XWPFTableCell cell : cells) {
                // 4.5 设置单元格样式
                // 获取单元格(cell)的属性对象(CTTcPr),该对象用于描述单元格的一些属性,例如宽度、边框、垂直对齐方式等。
                CTTcPr ctTcPr = cell.getCTTc().addNewTcPr();
                // 创建一个新的垂直对齐方式对象(CTVerticalJc),并将其添加到单元格属性对象中。
                CTVerticalJc ctVerticalJc = ctTcPr.addNewVAlign();
                // 设置垂直对齐方式对象的值为 "CENTER",将单元格中的内容垂直居中显示
                ctVerticalJc.setVal(STVerticalJc.CENTER);  // 枚举,可以有多种

                // 设置单元格阴影样式
                CTShd ctShd = ctTcPr.addNewShd();
                ctShd.setColor("auto");
                ctShd.setVal(STShd.CLEAR);  // 枚举,可以有多种

                // 头行和内容行的阴影颜色应有区别  (需要定义当前行和当前列的变量)
                if (currentRow == 0) {
                    ctShd.setFill("FFFFCC");
                } else {
                    ctShd.setFill("90EE90");
                }

                // 设置单元格中的内容样式
                XWPFParagraph xwpfParagraph = cell.getParagraphs().get(0);
                XWPFRun cellRun = xwpfParagraph.createRun();

                // 设置居中
                xwpfParagraph.setAlignment(ParagraphAlignment.CENTER);

                // 内容的样式也是需要区分头行和内容行的
                if (currentRow == 0) {
                    cellRun.setFontSize(18);
                    cellRun.setBold(true);
                    cellRun.setColor("FF0000");
                }

                // 设置单元格内容
                if (currentRow == 0) {
                    cellRun.setText("header" + (currentCol+1));
                } else {
                    cellRun.setText("content" + (currentCol+1));
                }

                currentCol++;
            }
            currentCol = 0;   // 一行中的单元格遍历结束后,需要恢复值为0
            currentRow++;
        }

        // 在这边也可以判断路径是否存在, 如果不存在, 则创建路径
        File path = new File(PATH);
        if (!path.exists()) {
            path.mkdirs();
        }

        // 创建文件对象
        File file = new File(PATH + "\\write_tableStyle.docx");
        //  创建输出流
        FileOutputStream fileOutputStream = new FileOutputStream(file);

        document.write(fileOutputStream);

        fileOutputStream.close();

        System.out.println("表格样式设置完成");
    }
}

POI:对Word的基本操作_第3张图片

4 写入图片

package com.example;

import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.*;

import java.io.FileInputStream;
import java.io.FileOutputStream;

/**
 * @Author:xiexu
 * @Date:2024/1/13 11:44
 */
public class Write_img {
    static String PATH = "D:\\Idea-projects\\POI_word";

    public static void main(String[] args) throws Exception {
        // 1. 定义一个图片路径
        String imgPath = "D:\\Idea-projects\\POI_word\\beag.png";

        // 2.  创建一个文件对象
        XWPFDocument document = new XWPFDocument();
        // 3.创建一个段落
        XWPFParagraph paragraph = document.createParagraph();
        //4.创建运行区域
        XWPFRun run = paragraph.createRun();
        // 5.写入图片
        // 将文件路径写入word文档
        run.setText("图片路径:" + imgPath);
        // 换行
        run.addBreak();

        // 增加图片到运行区域
        // 创建一个输入流
        FileInputStream fileInputStream = new FileInputStream(imgPath);
        run.addPicture(fileInputStream, Document.PICTURE_TYPE_PNG, imgPath, Units.toEMU(400), Units.toEMU(250));
        // 第一个参数是输入流、
        // 第二个参数是图片的类型、
        // 第三个参数是图片的路径、
        // 第四个参数是图片的宽度、
        // 第五个参数是图片的高度


        // 6.另起一个页面
        run.addBreak(BreakType.PAGE);

        // 7. 写入到磁盘
        // 创建一个输出流
        FileOutputStream outputStream = new FileOutputStream(PATH + "\\write_img.docx");
        document.write(outputStream);
        outputStream.close();

        System.out.println("图片写入完成");
    }
}

POI:对Word的基本操作_第4张图片


5 读取文档中内容

package com.exampleRead;

import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;

import java.io.File;
import java.io.FileInputStream;

/**
 * @Author:xiexu
 * @Date:2024/1/13 12:04
 */
public class ReadWord {
    public static void main(String[] args) throws Exception {
        // 找到用读取的目标文件
        File file = new File("D:\\Idea-projects\\POI_word\\write_word.docx");

        // 创建输入流,将文件写入输入流
        FileInputStream fileInputStream = new FileInputStream(file);

        // 创建一个文档对象,将输入流写入文档对象
        XWPFDocument document = new XWPFDocument(fileInputStream);

        // 创建一个文档执行器
        XWPFWordExtractor xwpfWordExtractor = new XWPFWordExtractor(document);

        // 输出文档内容
        String text = xwpfWordExtractor.getText();

        System.out.println(text);

        fileInputStream.close();
    }
}

POI:对Word的基本操作_第5张图片


读取目标文档中其它的属性信息 

POI:对Word的基本操作_第6张图片


 POI:对Word的基本操作_第7张图片


这些属性信息可以在创建文件的时候,可以设置进去

POI:对Word的基本操作_第8张图片


POI:对Word的基本操作_第9张图片

 

6 读取文档中的图片

package com.exampleRead;

import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFPicture;
import org.apache.poi.xwpf.usermodel.XWPFRun;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author:xiexu
 * @Date:2024/1/13 12:32
 */
public class Read_img {
    public static void main(String[] args) throws Exception {
        // 定义一个待读取的文件路径
        String filePath = "D:\\Idea-projects\\POI_word\\write_img.docx";

        File Path = new File(filePath);
        // 判断路径是否存在
        if (!Path.exists()) {
            System.out.println("文件不存在");
            return;
        }

        // 创建一个输入流
        FileInputStream fileInputStream = new FileInputStream(filePath);

        // 创建一个文档对象
        XWPFDocument document = new XWPFDocument(fileInputStream);

        // 定义一个HashMap来存储图片的信息
        Map ImagesHashMap = new HashMap<>();
        // 获取所有段落
        List paragraphs = document.getParagraphs();
        // 遍历所有段落
        for (XWPFParagraph paragraph : paragraphs) {
            List runs = paragraph.getRuns();
            for (XWPFRun run : runs) {
                // 获取运行区域的所有图片
                List pictures = run.getEmbeddedPictures();

                // 遍历图片
                for (XWPFPicture picture : pictures) {
                    // 我们需要定义一个HashMap来存储图片的信息
                    String fileName = picture.getPictureData().getFileName();
                    byte[] data = picture.getPictureData().getData();  // 是以二进制的形式

                    ImagesHashMap.put("D:\\Idea-projects\\POI_word\\poi1"+fileName, data);
                }
            }
        }

        // 遍历ImagesHashMap集合
        for (Map.Entry entry : ImagesHashMap.entrySet()) {
            String FilePathKey = entry.getKey();
            byte[] Filevalue = entry.getValue();

            System.out.println("开始写入图片...");
            // 创建一个输出流
            FileOutputStream fileOutputStream = new FileOutputStream(FilePathKey);
            fileOutputStream.write(Filevalue);
            fileOutputStream.close();

            System.out.println("图片写入完成...");
        }
    }
}

7 读取文档中表格的内容

package com.exampleRead;

import org.apache.poi.xwpf.usermodel.*;

import java.io.File;
import java.io.FileInputStream;
import java.util.List;

/**
 * @Author:xiexu
 * @Date:2024/1/13 13:01
 */
public class Read_table {
    public static void main(String[] args) throws Exception {

        // 定义一个待读取的文件路径
        String filePath = "D:\\Idea-projects\\POI_word\\write_tableStyle.docx";

        // 判断路径是否存在
        File pathCheck = new File(filePath);
        if (!pathCheck.exists()){
            System.out.println("文件路径不存在");
            return;
        }

        // 创建一个输入流
        FileInputStream fileInputStream = new FileInputStream(filePath);

        // 创建一个文档对象
        XWPFDocument document = new XWPFDocument(fileInputStream);

        // 获取表格对象
        List tables = document.getTables();
        // 遍历表格(因为一个文档中可能有多个表格)
        for (XWPFTable table : tables) {
            List rows = table.getRows();
            // 遍历所有的行
            for (XWPFTableRow row : rows) {
                List cells = row.getTableCells();
                // 遍历所有的单元格
                for (XWPFTableCell cell : cells) {
                    System.out.println("开始读取表格...");
                    // 获取内容
                    String text = cell.getText();
                    System.out.println("单元格中的内容是:" + text);
                }
            }
        }

        System.out.println("表格读取完毕");

        fileInputStream.close();
    }
}

POI:对Word的基本操作_第10张图片

 

你可能感兴趣的:(POI,java,word)