当前位置: 首页 > news >正文

java解析word文档

文章目录

  • 读取段落
  • 读取图片
  • 读取表格内容
  • 页码

读取段落

  读取段落内容非常简单。以下是一个demo:

public static void main(String[] args) {try(FileInputStream stream = new FileInputStream("parse/pages.docx")) {XWPFDocument document = new XWPFDocument(stream);List<XWPFParagraph> paragraphs = document.getParagraphs();for (XWPFParagraph paragraph: paragraphs) {System.out.println(paragraph.getText());}} catch (FileNotFoundException e) {throw new RuntimeException(e);} catch (IOException e) {throw new RuntimeException(e);}
}

  

读取图片

  读取word里的图片也不难了,只需要获取XWPFPictureData对象就可以了,然后就可以获取到图片内容的byte数组。


public static void main(String[] args) {try(FileInputStream stream = new FileInputStream("parse/pages.docx")) {XWPFDocument document = new XWPFDocument(stream);List<XWPFPictureData> allPictures = document.getAllPictures();for (XWPFPictureData pictureData: allPictures) {byte[] data = pictureData.getData();File file = new File(pictureData.getFileName());Files.write(file.toPath(), data);}} catch (FileNotFoundException e) {throw new RuntimeException(e);} catch (IOException e) {throw new RuntimeException(e);}
}

读取表格内容

  word中的表格,是XWPFTable-XWPFTableRow-XWPFTableCell的三级结构。有个这个三级结构,就非常好写代码获取了。

public static void main(String[] args) {try(FileInputStream stream = new FileInputStream("parse/table.docx")) {XWPFDocument document = new XWPFDocument(stream);List<XWPFTable> tables = document.getTables();for (XWPFTable table: tables) {List<XWPFTableRow> rows = table.getRows();for (XWPFTableRow row: rows) {List<XWPFTableCell> tableCells = row.getTableCells();for (XWPFTableCell cell: tableCells) {System.out.print(cell.getText());System.out.print("\t");}System.out.println();}}} catch (FileNotFoundException e) {throw new RuntimeException(e);} catch (IOException e) {throw new RuntimeException(e);}
}

页码

  实际工作中,解析word的场景少,生成word的场景多。但是如果有个需求是获取word特定一页的内容呢?比如说获取第9页内容,怎么办?可以说非常难实现,因为apache poi只能读取word底层的xml模型,实际的页码需要渲染才知道。

http://www.lryc.cn/news/590185.html

相关文章:

  • 使用JS编写一个购物车界面
  • C++ 面向对象
  • 第2章通用的高并发架构设计——2.3 高并发读场景方案2:本地缓存
  • 开源 python 应用 开发(七)数据可视化
  • Linux 定时器应用示例(修正版)
  • GIT版本回退
  • Python中可以反转的数据类型
  • GaussDB 数据库架构师修炼(五) 存储容量评估
  • 搜索框的显示与隐藏(展开与收起)
  • el-input 回显怎么用符号¥和变量拼接展示?
  • openEuler 22.03 LTS Rootless Docker 安装指南
  • MongoDB复杂查询 聚合框架
  • 洛谷 P11247 [GESP202409 六级] 算法学习-普及/提高-
  • pymongo库:简易方式存取数据
  • ETL还是ELT,大数据处理怎么选更靠谱?
  • 步态循环(Gait Cycle)
  • 【MySQL事务和锁】回顾事务
  • 图像质量评价(Image Quality Assessment,IQA)
  • 调试bug记录
  • 【基于飞浆训练车牌识别模型】
  • Docker——Redis
  • 【C语言网络编程】HTTP 客户端请求(发送请求报文过程)
  • Mybatis07-缓存
  • 比特币技术简史 第二章:密码学基础 - 哈希函数、公钥密码学与数字签名
  • 今日行情明日机会——20250716
  • S7-200 SMART PLC:模拟量模块接线全解析
  • 汽车功能安全-相关项集成和测试(系统集成测试系统合格性测试)-12
  • xss-labs通关
  • “Datawhale AI夏令营”基于带货视频评论的用户洞察挑战赛2
  • lesson15:Python的文件操作