读取word文档表格解析工具类

import com.cmft.fhris.app.basic.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.model.PicturesTable;
import org.apache.poi.hwpf.usermodel.*;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.xwpf.usermodel.*;

import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.cmft.fhris.app.business.licence.constant.LicneceErrorMsgConstant.LICENCE_IO_ERROR_LOG_MSG;
import static com.cmft.fhris.app.business.licence.constant.LicneceErrorMsgConstant.READ_WORD_ERROR_MSG;

/**
 * 读取word文档工具类
 */
@Slf4j
public class ReadWordUtil {
    
    /**
     * 根据输入流读取word文件 将表格数据转List数据结构
     *
     * @param in
     * @param wordType
     * @return
     */
    public static List<String[]> getWordTableInputStream(FileInputStream in, String filePath, Integer wordType) {
        List<String[]> tabRowList = new ArrayList(); // 表格行集合
        try {
            int tableCount = 1;
            // 处理docx格式 即office2007以后版本
            if (filePath.toLowerCase().endsWith("docx")) {
                //word 2007 图片不会被读取, 表格中的数据会被放在字符串的最后
                //得到word文档的信息
                XWPFDocument xwpf = new XWPFDocument(in);
                //得到word中的表格
                Iterator<XWPFTable> it = xwpf.getTablesIterator();
                while (it.hasNext()) {
                    //只读取第一个表格数据
                    if (1 == tableCount) {
                        XWPFTable table = it.next();
                        List<XWPFTableRow> rows = table.getRows();
                        //读取每一行数据
                        for (int i = 0; i < rows.size(); i++) {
                            XWPFTableRow row = rows.get(i);
                            //读取每一列数据
                            List<XWPFTableCell> cells = row.getTableCells();
                            //当前行列数
                            int numCells = cells.size();
                            String[] cellArr = new String[numCells];
                            for (int j = 0; j < numCells; j++) {
                                XWPFTableCell cell = cells.get(j);
                                if (2 == wordType && i == 0 && j == 6) {
                                    cellArr[j] = getCellImageByDocs(cell);
                                } else {
                                    //取得单元格的内容
                                    String cellContent = "";
                                    List<XWPFParagraph> paragraphs = cell.getParagraphs();
                                    for (int k = 0; k < paragraphs.size(); k++) {
                                        XWPFParagraph para = paragraphs.get(k);
                                        cellContent = StringUtils.isBlank(cellContent) ? para.getText().trim() : cellContent + para.getText().trim();
                                    }
                                    //去除字符串中的空格、回车、换行符、制表符
                                    Pattern p = Pattern.compile("\\s*|\t|\r|\n");
                                    Matcher m = p.matcher(cellContent);
                                    cellArr[j] = m.replaceAll("");
                                }
                            }
                            tabRowList.add(cellArr);
                        }
                    }
                    tableCount++;
                }
            } else {
                // 处理doc格式 即office2003版本
                POIFSFileSystem pfs = new POIFSFileSystem(in);
                //获取文档操作对象
                HWPFDocument hwpf = new HWPFDocument(pfs);
                //获取文档操作区间
                Range range = hwpf.getRange();
                //获取表格迭代器
                TableIterator it = new TableIterator(range);
                while (it.hasNext()) {
                    //只读取第一个表格数据
                    if (1 == tableCount) {
                        //获取word中表格
                        Table tb = it.next();
                        for (int i = 0; i < tb.numRows(); i++) {
                            //获取行数
                            TableRow tr = tb.getRow(i);
                            //当前行列数
                            int numCells = tr.numCells();
                            String[] cellArr = new String[tr.numCells()];
                            for (int j = 0; j < numCells; j++) {
                                TableCell tc = tr.getCell(j);
                                if (2 == wordType && i == 0 && j == 6) {
                                    PicturesTable picturesTable = hwpf.getPicturesTable();
                                    cellArr[j] = getCellImageByDoc(tc, picturesTable);
                                } else {
                                    //取得单元格的内容
                                    String cellContent = "";
                                    for (int k = 0; k < tc.numParagraphs(); k++) {
                                        Paragraph para = tc.getParagraph(k);
                                        cellContent = StringUtils.isBlank(cellContent) ? para.text().trim() : cellContent + para.text().trim();
                                    }
                                    //去除字符串中的空格、回车、换行符、制表符
                                    Pattern p = Pattern.compile("\\s*|\t|\r|\n");
                                    Matcher m = p.matcher(cellContent);
                                    cellArr[j] = m.replaceAll("");
                                }
                            }
                            tabRowList.add(cellArr);
                        }
                    }
                    tableCount++;
                }
            }
        } catch (Exception e) {
            log.error(LICENCE_IO_ERROR_LOG_MSG, e.getMessage(), e);
            throw new BusinessException(READ_WORD_ERROR_MSG);
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                log.error(LICENCE_IO_ERROR_LOG_MSG, e.getMessage(), e);
                throw new BusinessException(READ_WORD_ERROR_MSG);
            }
        }
        return tabRowList;
    }

    /**
     * 功能描述:获取单元格中的图片数据
     */
    public static String getCellImageByDoc(TableCell cell, PicturesTable picturesTable) {
        CharacterRun cr = cell.getCharacterRun(0);
        if (picturesTable.hasPicture(cr)) {
            Picture pic = picturesTable.extractPicture(cr, true);
            byte[] picbyte = pic.getContent();
            String fileName = UUID.randomUUID().toString() + ".jpg";
            String tmpDir = System.getProperty("java.io.tmpdir");
            String filePath = tmpDir + fileName;
            File file = byte2File(picbyte, filePath);
            return file.getAbsolutePath();
        }
        return "";
    }

    /**
     * 功能描述:获取单元格中的图片数据
     */
    public static String getCellImageByDocs(XWPFTableCell cell) {
        List<XWPFParagraph> xwpfParagraphs = cell.getParagraphs();
        if (xwpfParagraphs == null) {
            return null;
        }
        for (XWPFParagraph xwpfParagraph : xwpfParagraphs) {
            List<XWPFRun> xwpfRunList = xwpfParagraph.getRuns();
            if (xwpfRunList == null) {
                return null;
            }
            for (XWPFRun xwpfRun : xwpfRunList) {
                List<XWPFPicture> xwpfPictureList = xwpfRun.getEmbeddedPictures();
                if (xwpfPictureList == null) {
                    return null;
                }
                for (XWPFPicture xwpfPicture : xwpfPictureList) {
                    String fileName = UUID.randomUUID().toString() + ".jpg";
                    String tmpDir = System.getProperty("java.io.tmpdir");
                    String filePath = tmpDir + fileName;
                    File file = byte2File(xwpfPicture.getPictureData().getData(), filePath);
                    return file.getAbsolutePath();
                }
            }
        }
        return "";
    }

    /**
     * 根据byte数组,生成文件
     *
     * @param bfile    文件数组
     * @param filePath 文件存放路径
     */
    public static File byte2File(byte[] bfile, String filePath) {
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        File file = null;
        try {
            file = new File(filePath);
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(bfile);
            return file;
        } catch (Exception e) {
            log.error(LICENCE_IO_ERROR_LOG_MSG, e.getMessage(), e);
            throw new BusinessException(READ_WORD_ERROR_MSG);
        } finally {
            try {
                if (bos != null) {
                    bos.close();
                }
                if (fos != null) {
                    fos.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Matlab是一个功能强大的数学软件,它可以读取Word中的表格。具体操作如下: 首先,我们需要在Matlab中安装支持Word文档工具箱。我们可以打开Matlab的主界面,然后选择“Add-Ons”选项。在弹出的窗口中,我们可以搜索并安装名为“Text Analytics Toolbox”的工具箱。 安装完成后,我们可以打开Word文档并选择需要读取表格。然后,我们可以使用Word软件将选定的表格复制到剪贴板中。 接下来,我们可以在Matlab中使用以下代码将表格粘贴到Matlab工作空间中: T = readtable('clipboard', 'Delimiter', '\t'); 这行代码将剪贴板中的表格读取为一个表格变量T,并将它保存在Matlab的工作区中。在这里,我们使用'tab'分隔符来解析表格。如果表格中使用其他分隔符,我们需要相应地更改分隔符参数。 此外,我们可以在读取表格之前,使用以下代码打开一个Word文档: word = actxserver('Word.Application'); word.Visible = true; 这将启动一个新的Word应用程序实例,并使它可见。然后我们可以使用以下代码选择要读取表格: selection = word.Selection; table_range = selection.Tables.Item(1).Range; table_range.Copy; 这行代码将选定的表格复制到剪贴板中,以使用第一行代码读取Matlab中的表格。 总之,使用Matlab读取Word中的表格需要安装一个支持Word文档工具箱。然后我们可以复制表格到剪贴板中,使用Matlab读取表格,并将其保存到Matlab工作环境中。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值