通过POI对Word文档中的表格数据及图片进行处理并入库(支持DOCX及DOC)

引入依赖

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

定义相关对象

import lombok.Data;
import java.io.Serializable;

/**
 * @Author: yz
 * @Description:
 */
@Data
public class FieldInfo implements Serializable {

    // 字段名称
    private String fieldName;
    // 所在表格
    private Integer tableIndex;
    // 所在行
    private Integer row;
    // 所在列
    private Integer cell;
    // 字段类型 1-数字类型,2-图片,3-普通字符,4-Boolean
    private String fieldType;
    // 图片下标
    private Integer pictureIndex;
    // 图片路径
    private String picturePath;
}
import lombok.Data;
import java.io.Serializable;
import java.util.List;

/**
 * @Author: yz
 * @Description:
 */
@Data
public class ImportEntity implements Serializable {

    private List<FieldInfo> fieldInfos;
}

准备模板

在这里插入图片描述

导入导出代码


import com.example.demo.entity.FieldInfo;
import com.example.demo.entity.ImportEntity;
import com.example.demo.handler.MyInvocationHandler;
import org.apache.ibatis.session.SqlSession;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.*;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.xwpf.usermodel.*;
import org.springframework.cglib.proxy.InvocationHandler;
import org.springframework.cglib.proxy.Proxy;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: yz
 * @Description:
 */
public class ImportCommonUtil {
    private static final String STARTS_WITH = "${";

    private static final String END_WITH = "}";


    /**
     * 获取导入对象字段信息
     *
     * @param filePath
     * @return
     */
    private static ImportEntity getImportEntity(String filePath) {
        ImportEntity importEntity = new ImportEntity();
        List<FieldInfo> fieldInfos = new ArrayList<>();
        importEntity.setFieldInfos(fieldInfos);
        try {
            // 读取文档
            FileInputStream in = new FileInputStream(filePath);
            // 按照文档格式处理
            if (filePath.toLowerCase().endsWith("docx")) {
                // 得到word文档的信息 -> 2007
                XWPFDocument xwpf = new XWPFDocument(in);
                List<XWPFTable> tables = xwpf.getTables();
                tables.stream().forEach(table -> {
                    int indexOfTable = tables.indexOf(table);
                    List<XWPFTableRow> rows = table.getRows();
                    rows.stream().forEach(row -> {
                        int indexOfRow = rows.indexOf(row);
                        List<XWPFTableCell> tableCells = row.getTableCells();
                        for (int i = 0; i < tableCells.size(); i++) {
                            XWPFTableCell xwpfTableCell = tableCells.get(i);
                            String text = xwpfTableCell.getText();
                            if (xwpfTableCell.getText().startsWith(STARTS_WITH)) {
                                FieldInfo fieldInfo = new FieldInfo();
                                fieldInfo.setTableIndex(indexOfTable);
                                fieldInfo.setRow(indexOfRow);
                                fieldInfo.setCell(i);
                                String fieldName = text.replace(STARTS_WITH, "").replace(END_WITH, "");
                                fieldInfo.setFieldName(fieldName);
                                fieldInfos.add(fieldInfo);
                            }
                        }
                    });
                });
            } else {
                // 处理doc格式 -> 2003版本
                POIFSFileSystem pfs = new POIFSFileSystem(in);
                HWPFDocument hwpf = new HWPFDocument(pfs);
                // 得到文档的读取范围
                Range range = hwpf.getRange();
                TableIterator tableIterator = new TableIterator(range);
                Integer total = 0;
                while (tableIterator.hasNext()) {
                    Table table = tableIterator.next();
                    total += 1;
                    int numRows = table.numRows();
                    for (int i = 0; i < numRows; i++) {
                        TableRow row = table.getRow(i);
                        int numCells = row.numCells();
                        for (int j = 0; j < numCells; j++) {
                            TableCell cell = row.getCell(j);
                            String text = cell.text();
                            if (text.startsWith(STARTS_WITH)) {
                                FieldInfo fieldInfo = new FieldInfo();
                                fieldInfo.setTableIndex(total + 1);
                                fieldInfo.setRow(i);
                                fieldInfo.setCell(j);
                                String fieldName = text.substring(text.indexOf("{"), text.indexOf(END_WITH));
                                fieldInfo.setFieldName(fieldName);
                                fieldInfos.add(fieldInfo);
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return importEntity;
    }
/*
    private static <T> void batchSave(Class<T> tClass, List<T> dataList) {
        // 获取Mapper地址
        try {
            SqlSession sqlSession = MyBatisUtils.openSession();
            String mapper = tClass.getSimpleName() + "Mapper";
            //这里要写全类名
            Class interfaceImpl = Class.forName(mapper);
            Object instance = Proxy.newProxyInstance(
                    interfaceImpl.getClassLoader(),
                    new Class[]{interfaceImpl},
                    (InvocationHandler) new MyInvocationHandler(sqlSession.getMapper(interfaceImpl))
            );

            Method method = instance.getClass().getMethod("batchSave", List.class);
            method.invoke(instance, dataList);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }*/

    /**
     * 读取文档中表格并获取对象数据
     *
     * @param filePath
     * @param list
     * @param tClass
     * @param <T>
     * @return
     */
    public static <T> List<T> tableInWord(String filePath, List<ImportEntity> list, Class<T> tClass) {
        return list.stream().map(importEntity -> {
            return getInstance(filePath, tClass, importEntity);
        }).collect(Collectors.toList());
    }

    private static <T> T getInstance(String filePath, Class<T> tClass, ImportEntity importEntity) {
        List<FieldInfo> fieldInfos = importEntity.getFieldInfos();
        T newInstance = null;
        try {
            newInstance = tClass.newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        try {
            //载入文档
            FileInputStream in = new FileInputStream(filePath);
            // 处理docx格式 即office2007以后版本
            if (filePath.toLowerCase().endsWith("docx")) {
                //word 2007 图片不会被读取, 表格中的数据会被放在字符串的最后
                //得到word文档的信息
                XWPFDocument xwpf = new XWPFDocument(in);
                List<XWPFTable> tables = xwpf.getTables();
                List<XWPFPictureData> pictures = xwpf.getAllPictures();
                for (FieldInfo fieldInfo : fieldInfos) {
                    XWPFTableCell cell = tables.get(fieldInfo.getTableIndex()).getRow(fieldInfo.getRow()).getCell(fieldInfo.getCell());
                    Field field = null;
                    try {
                        field = tClass.getField(fieldInfo.getFieldName());
                    } catch (NoSuchFieldException e) {
                        e.printStackTrace();
                    }
                    field.setAccessible(true);
                    String fieldType = fieldInfo.getFieldType();
                    try {
                        if ("1".equals(fieldType)) {
                            field.set(newInstance, Integer.valueOf(cell.getText()));
                        } else if ("2".equals(fieldType)) {
                            String url = pictureTQDocx(pictures.get(fieldInfo.getPictureIndex()), fieldInfo.getPicturePath());
                            field.set(newInstance, url);
                        } else if ("3".equals(fieldType)) {
                            field.set(newInstance, cell.getText());
                        } else if ("4".equals(fieldType)) {
                            field.set(newInstance, Boolean.valueOf(cell.getText()));
                        }
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            } else {
                // 处理doc格式 即office2003版本
                POIFSFileSystem pfs = new POIFSFileSystem(in);
                HWPFDocument hwpf = new HWPFDocument(pfs);
                List<Picture> allPictures = hwpf.getPicturesTable().getAllPictures();
                //得到文档的读取范围
                Range range = hwpf.getRange();
                TableIterator tableIterator = new TableIterator(range);
                //得到word中的表格
                Map<Integer, Table> tableMap = new HashMap<>();
                Integer total = 0;
                while (tableIterator.hasNext()) {
                    Table next = tableIterator.next();
                    Integer key = total;
                    total += 1;
                    tableMap.put(key, next);
                }
                for (FieldInfo fieldInfo : fieldInfos) {
                    Table table = tableMap.get(fieldInfo.getTableIndex());
                    TableCell cell = table.getRow(fieldInfo.getRow()).getCell(fieldInfo.getCell());
                    Field field = null;
                    try {
                        field = tClass.getField(fieldInfo.getFieldName());
                    } catch (NoSuchFieldException e) {
                        e.printStackTrace();
                    }
                    field.setAccessible(true);
                    String fieldType = fieldInfo.getFieldType();
                    try {
                        if ("1".equals(fieldType)) {
                            field.set(newInstance, Integer.valueOf(cell.text()));
                        } else if ("2".equals(fieldType)) {
                            String url = pictureTQDoc(allPictures.get(fieldInfo.getPictureIndex()), fieldInfo.getPicturePath());
                            field.set(newInstance, url);
                        } else if ("3".equals(fieldType)) {
                            field.set(newInstance, cell.text());
                        } else if ("4".equals(fieldType)) {
                            field.set(newInstance, Boolean.valueOf(cell.text()));
                        }
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return newInstance;
    }

    /**
     * 提取DOCX图片,并保存,返回可访问路径
     *
     * @param picture
     * @param resourceBaseUrl
     * @return
     * @throws IOException
     */
    public static String pictureTQDocx(XWPFPictureData picture, String resourceBaseUrl) throws IOException {
        FileOutputStream fileOutputStream;
        StringBuilder picturePath = getPicturePathBuilder(resourceBaseUrl);
        picturePath.append(System.currentTimeMillis()).append(".").append(picture.suggestFileExtension());
        String string = picturePath.toString();
        fileOutputStream = new FileOutputStream(new File(resourceBaseUrl + string));
        fileOutputStream.write(picture.getData());
        return string;
    }

    /**
     * 提取DOC图片,并保存,返回可访问路径
     *
     * @param picture
     * @param resourceBaseUrl
     * @return
     * @throws IOException
     */
    public static String pictureTQDoc(Picture picture, String resourceBaseUrl) throws IOException {
        FileOutputStream fileOutputStream = null;
        String path = null;
        try {
            StringBuilder picturePath = getPicturePathBuilder(resourceBaseUrl);
            picturePath.append(System.currentTimeMillis()).append(picture.suggestFullFileName());
            path = picturePath.toString();
            fileOutputStream = new FileOutputStream(new File(resourceBaseUrl + path));
            picture.writeImageContent(fileOutputStream);
            fileOutputStream.close();
        } finally {
            if (fileOutputStream != null) {
                fileOutputStream.close();
            }
            return path;
        }
    }

    private static StringBuilder getPicturePathBuilder(String resourcePath) {
        StringBuilder append = new StringBuilder().append("ufop")
                .append(File.separator)
                .append("img")
                .append(File.separator)
                .append(DateUtil.DateFormatYearMonthDay(new Date()))
                .append(File.separator);
        File file = new File(resourcePath + append);
        if (!file.exists() && !file.isDirectory()) {
            file.mkdirs();
        }
        return append;
    }
}

欢迎大家提出宝贵的意见

### 回答1: 要使用POI获取Word文档表格数据,可以按照以下步骤进行: 1. 首先,使用POI库打开Word文档。例如,使用XWPFDocument类打开.docx文件。 ```java FileInputStream fis = new FileInputStream("example.docx"); XWPFDocument doc = new XWPFDocument(fis); ``` 2. 然后,使用getTables()方法获取文档的所有表格,该方法返回一个XWPFTable的List。 ```java List<XWPFTable> tables = doc.getTables(); ``` 3. 对于每个表格,使用getRows()方法获取表格的所有行,该方法返回一个XWPFTableRow的List。 ```java for(XWPFTable table : tables) { List<XWPFTableRow> rows = table.getRows(); for(XWPFTableRow row : rows) { // 处理数据 } } ``` 4. 对于每一行,使用getTableCells()方法获取该行的所有单元格,该方法返回一个XWPFTableCell的List。 ```java for(XWPFTable table : tables) { List<XWPFTableRow> rows = table.getRows(); for(XWPFTableRow row : rows) { List<XWPFTableCell> cells = row.getTableCells(); for(XWPFTableCell cell : cells) { // 处理单元格数据 } } } ``` 5. 对于每个单元格,使用getText()方法获取单元格的文本内容。 ```java for(XWPFTable table : tables) { List<XWPFTableRow> rows = table.getRows(); for(XWPFTableRow row : rows) { List<XWPFTableCell> cells = row.getTableCells(); for(XWPFTableCell cell : cells) { String text = cell.getText(); // 处理单元格的文本内容 } } } ``` 这样就可以获取Word文档所有表格的所有行和单元格的数据了。 ### 回答2: 使用Java利用POI获取Word文档表格数据,可以通过以下步骤实现: 1. 导入POI库:首先需要在Java项目导入POI库,并将库文件添加到项目的classpath。 2. 加载Word文档:使用POI的XWPFDocument类加载Word文档,代码如下: ```java InputStream in = new FileInputStream("path/to/word/document.docx"); XWPFDocument doc = new XWPFDocument(in); ``` 3. 获取所有表格:通过getTables()方法获取Word文档的所有表格,代码如下: ```java List<XWPFTable> tables = doc.getTables(); ``` 4. 遍历表格:可以使用循环遍历所有表格,根据需要进行操作,例如获取表格数据等。 ```java for (XWPFTable table : tables) { // 获取表格的行 List<XWPFTableRow> rows = table.getRows(); // 遍历行 for (XWPFTableRow row : rows) { // 获取行的单元格 List<XWPFTableCell> cells = row.getTableCells(); // 遍历单元格 for (XWPFTableCell cell : cells) { // 获取单元格的内容 String content = cell.getText(); // 处理单元格数据,例如打印或保存到其他地方 System.out.println(content); } } } ``` 通过以上步骤,可以使用Java利用POI获取Word文档表格数据。根据实际需求,可以对获取到的数据进行处理,例如保存到数据库或生成其他格式的文档。 ### 回答3: Java利用POI可以很方便地获取Word文档表格数据。下面是实现的步骤: 1. 导入POI库:首先需要在Java工程导入POI的相关库文件,可以使用Maven或手动下载并导入。 2. 创建Word文档对象:使用XWPFDocument类创建一个Word文档对象,打开需要解析的Word文档。 3. 获取文档表格:使用getTables()方法获取文档所有的表格,返回一个List对象。 4. 遍历表格:使用for循环遍历表格列表,可以通过getTable()方法获取每个表格。 5. 获取表格的行并遍历:使用getRows()方法获取表格所有的行,返回一个List对象。然后使用for循环遍历行列表,可以通过getRow()方法获取每一行。 6. 获取行的单元格并遍历:使用getTableCells()方法获取行所有的单元格,返回一个List对象。然后使用for循环遍历单元格列表,可以通过getTableCell()方法获取每个单元格。 7. 获取单元格的文本:使用getText()方法获取单元格的文本内容。 完整的示例代码如下: ```java import org.apache.poi.xwpf.usermodel.*; import java.io.FileInputStream; import java.io.IOException; import java.util.List; public class ReadTableData { public static void main(String[] args) { try { // 创建Word文档对象 XWPFDocument document = new XWPFDocument(new FileInputStream("example.docx")); // 获取文档的所有表格 List<XWPFTable> tables = document.getTables(); // 遍历表格 for (XWPFTable table : tables) { // 获取表格的所有行 List<XWPFTableRow> rows = table.getRows(); // 遍历行 for (XWPFTableRow row : rows) { // 获取行的所有单元格 List<XWPFTableCell> cells = row.getTableCells(); // 遍历单元格 for (XWPFTableCell cell : cells) { // 获取单元格的文本内容 String text = cell.getText(); System.out.println(text); } } } // 关闭文档 document.close(); } catch (IOException e) { e.printStackTrace(); } } } ``` 以上就是使用POI库获取Word文档表格数据的基本步骤和示例代码。通过POI的各种API可以更加灵活地处理表格数据,比如可以合并、拆分单元格,修改样式等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值