使用POI读写Word文件(兼容doc与docx版本)

调用示例:

 

File wordFile = new File("D:\\temp.doc");

//读取Word文档中所有文本内容,以字符串形式返回
System.out.println(WordFileUtil.extractTextFromWordFile(wordFile));

 

工具类源码:

 

Word2003版本工具类:

 

/**
 * Word2003FileUtil.java
 * Copyright ® 2010 窦海宁
 * All right reserved
 */

package org.aiyu.core.common.util.file.office;

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

import org.apache.commons.io.IOUtils;
import org.apache.poi.hwpf.extractor.WordExtractor;

/**
 * <p>Word2003版文件工具类
 * 
 * <p>通用的Word2003版文件工具类,可用于从Word文档中抽取文本信息
 * 
 * @author  窦海宁, chong0660@sina.com
 * @since   AiyuCommonCore-1.0
 * @version AiyuCommonCore-1.0
 */
public abstract class Word2003FileUtil {

	/**
	 * <
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
POI(Apache POI)是一个用于读写 Microsoft Office 格式文件Java 库。使用 POI 可以方便地读取、创建和修改 Word、Excel 和 PowerPoint 文档。 使用 POI 创建 Word 文档时,可以使用 Word 模板来实现快速生成具有相同格式和布局的文档。 以下是使用 POI 使用 Word 模板创建 Word 文档的步骤: 1. 创建一个空的 Word 文档对象 ``` XWPFDocument doc = new XWPFDocument(); ``` 2. 打开 Word 模板文件 ``` FileInputStream inputStream = new FileInputStream("template.docx"); XWPFDocument templateDoc = new XWPFDocument(inputStream); ``` 3. 遍历模板中的段落,并复制到新的 Word 文档对象中 ``` for (XWPFParagraph templateParagraph : templateDoc.getParagraphs()) { XWPFParagraph newParagraph = doc.createParagraph(); newParagraph.getCTP().setPPr(templateParagraph.getCTP().getPPr()); for (XWPFRun templateRun : templateParagraph.getRuns()) { XWPFRun newRun = newParagraph.createRun(); newRun.getCTR().setRPr(templateRun.getCTR().getRPr()); newRun.setText(templateRun.getText(0)); } } ``` 4. 遍历模板中的表格,并复制到新的 Word 文档对象中 ``` for (XWPFTable templateTable : templateDoc.getTables()) { XWPFTable newTable = doc.createTable(); newTable.getCTTbl().setTblPr(templateTable.getCTTbl().getTblPr()); for (int i = 0; i < templateTable.getRows().size(); i++) { XWPFTableRow templateRow = templateTable.getRow(i); XWPFTableRow newRow = newTable.createRow(); newRow.getCTRow().setTrPr(templateRow.getCTRow().getTrPr()); for (int j = 0; j < templateRow.getTableCells().size(); j++) { XWPFTableCell templateCell = templateRow.getCell(j); XWPFTableCell newCell = newRow.getCell(j); newCell.getCTTc().setTcPr(templateCell.getCTTc().getTcPr()); newCell.setText(templateCell.getText()); } } } ``` 5. 关闭 Word 模板文件 ``` templateDoc.close(); ``` 6. 保存新的 Word 文档对象到文件 ``` FileOutputStream outputStream = new FileOutputStream("output.docx"); doc.write(outputStream); outputStream.close(); ``` 注意:以上代码中的 `template.docx` 是 Word 模板文件的路径,`output.docx` 是生成的新 Word 文档文件的路径。在复制段落和表格时,需要注意复制段落和表格的格式和样式,以确保生成的新文档与模板文档的格式和样式一致。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值