讀取Word中的表格

首先在pom.xml中引入POI

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

編寫如下代碼即可讀取Word中表格的內容,支持合併的單元格

import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTDecimalNumber;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTcPr;

/**
 * 讀取word中的表格,包括複雜表格(合併的單元格)
 */
public class ReadWordTable {

    /**
     * 保存生成HTML時需要被忽略的單元格
     */
    private List<String> omitCellsList = new ArrayList<>();

    /**
     * 生成忽略的單元格列表中的格式
     * 
     * @param row
     * @param col
     * @return
     */
    public String generateOmitCellStr(int row, int col) {
        return row + ":" + col;
    }

    /**
     * 獲取當前單元格的colspan(列合併)的列數
     * 
     * @param tcPr 單元格屬性
     * @return
     */
    public int getColspan(CTTcPr tcPr) {
        // 判斷是否存在列合併
        CTDecimalNumber gridSpan = null;
        if ((gridSpan = tcPr.getGridSpan()) != null) { // 合併的起始列
            // 獲取合併的列數
            BigInteger num = gridSpan.getVal();
            return num.intValue();
        } else { // 其他被合併的列或正常列
            return 1;
        }
    }

    /**
     * 獲取當前單元格的rowspan(行合併)的行數
     * 
     * @param table 表格
     * @param row 行值
     * @param col 列值
     * @return
     */
    public int getRowspan(XWPFTable table, int row, int col) {

        XWPFTableCell cell = table.getRow(row).getCell(col);
        // 正常獨立單元格
        if (!isContinueRow(cell) && !isRestartRow(cell)) {
            return 1;
        }
        // 當前單元格的寬度
        int cellWidth = getCellWidth(table, row, col);
        // 當前單元格距離左側邊框的距離
        int leftWidth = getLeftWidth(table, row, col);

        // 用戶保存當前單元格行合併的單元格數-1(因爲不包含自身)
        List<Boolean> list = new ArrayList();
        getRowspan(table, row, cellWidth, leftWidth, list);

        return list.size() + 1;
    }

    private void getRowspan(XWPFTable table, int row, int cellWidth, int leftWidth,
            List<Boolean> list) {
        // 已達到最後一行
        if (row + 1 >= table.getNumberOfRows()) {
            return;
        }
        row = row + 1;
        int colsNum = table.getRow(row).getTableCells().size();
        // 因爲列合併單元格可能導致行合併的單元格並不在同一列,所以從頭遍歷列,通過屬性、寬度以及距離左邊框間距來判斷是否是行合併
        for (int i = 0; i < colsNum; i++) {
            XWPFTableCell testTable = table.getRow(row).getCell(i);
            // 是否爲合併單元格的中間行(包括結尾行)
            if (isContinueRow(testTable)) {
                // 是被上一行單元格合併的單元格
                if (getCellWidth(table, row, i) == cellWidth
                        && getLeftWidth(table, row, i) == leftWidth) {
                    list.add(true);
                    // 被合併的單元格在生成html時需要忽略
                    addOmitCell(row, i);
                    // 去下一行繼續查找
                    getRowspan(table, row, cellWidth, leftWidth, list);
                    break;
                }
            }
        }
    }

    /**
     * 判斷是否是合併行的起始行單元格
     * 
     * @param tableCell
     * @return
     */
    public boolean isRestartRow(XWPFTableCell tableCell) {
        CTTcPr tcPr = tableCell.getCTTc().getTcPr();
        if (tcPr.getVMerge() == null) {
            return false;
        }
        if (tcPr.getVMerge().getVal() == null) {
            return false;
        }
        if (tcPr.getVMerge().getVal().toString().equalsIgnoreCase("restart")) {
            return true;
        }
        return false;
    }

    /**
     * 判斷是否是合併行的中間行單元格(包括結尾的最後一行的單元格)
     * 
     * @param tableCell
     * @return
     */
    public boolean isContinueRow(XWPFTableCell tableCell) {
        CTTcPr tcPr = tableCell.getCTTc().getTcPr();
        if (tcPr.getVMerge() == null) {
            return false;
        }
        if (tcPr.getVMerge().getVal() == null) {
            return true;
        }
        return false;
    }

    public int getLeftWidth(XWPFTable table, int row, int col) {
        int leftWidth = 0;
        for (int i = 0; i < col; i++) {
            leftWidth += getCellWidth(table, row, i);
        }
        return leftWidth;
    }

    public int getCellWidth(XWPFTable table, int row, int col) {
        BigInteger width = table.getRow(row).getCell(col).getCTTc().getTcPr().getTcW().getW();
        return width.intValue();
    }

    /**
     * 添加忽略的單元格(被行合併的單元格,生成HTML時需要忽略)
     * 
     * @param row
     * @param col
     */
    public void addOmitCell(int row, int col) {
        String omitCellStr = generateOmitCellStr(row, col);
        omitCellsList.add(omitCellStr);
    }

    public boolean isOmitCell(int row, int col) {
        String cellStr = generateOmitCellStr(row, col);
        return omitCellsList.contains(cellStr);
    }

    public String readTable(XWPFTable table) throws IOException {
        // 表格行數
        int tableRowsSize = table.getRows().size();
        StringBuilder tableToHtmlStr = new StringBuilder("<table>");

        for (int i = 0; i < tableRowsSize; i++) {
            tableToHtmlStr.append("<tr>");
            int tableCellsSize = table.getRow(i).getTableCells().size();
            for (int j = 0; j < tableCellsSize; j++) {
                if (isOmitCell(i, j)) {
                    continue;
                }
                XWPFTableCell tableCell = table.getRow(i).getCell(j);
                // 獲取單元格的屬性
                CTTcPr tcPr = tableCell.getCTTc().getTcPr();
                int colspan = getColspan(tcPr);
                if (colspan > 1) { // 合併的列
                    tableToHtmlStr.append("<td colspan='" + colspan + "'");
                } else { // 正常列
                    tableToHtmlStr.append("<td");
                }

                int rowspan = getRowspan(table, i, j);
                if (rowspan > 1) { // 合併的行
                    tableToHtmlStr.append(" rowspan='" + rowspan + "'>");
                } else {
                    tableToHtmlStr.append(">");
                }
                String text = tableCell.getText();
                tableToHtmlStr.append(text + "</td>");
            }
            tableToHtmlStr.append("</tr>");
        }
        tableToHtmlStr.append("</table>");
        clearTableInfo();
        return tableToHtmlStr.toString();
    }

    public void clearTableInfo() {
        omitCellsList.clear();
    }

    public static void main(String[] args) {
        ReadWordTable readWordTable = new ReadWordTable();
        try (FileInputStream fileInputStream = new FileInputStream("測試.docx");
                XWPFDocument document = new XWPFDocument(fileInputStream);) {
            List<XWPFTable> tables = document.getTables();
            for (XWPFTable table : tables) {
                System.out.println(readWordTable.readTable(table));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章