在Java中,你可以使用Apache POI库来读取Word文档并提取文本内容。你可以在 Maven 项目中添加以下依赖:
<!-- Apache POI for Word 2007+ (.docx) -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
<!-- Apache POI for Word 97-2003 (.doc) -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>4.1.2</version>
</dependency>
以下是一个简单的示例代码,展示如何使用Apache POI将Word文档转换为文本:
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
@Slf4j
public class WordUtils {
/**
* Word转换为文本
*
* @param file Word文件
* @return 提取的文本
*/
public static String wordToTextConverter(MultipartFile file) {
try {
if (file.getOriginalFilename().endsWith(".doc")) {
// 处理Word 97-2003文档
return processOldWordDocument(file);
} else if (file.getOriginalFilename().endsWith(".docx")) {
// 处理Word 2007及以上文档
return processNewWordDocument(file);
} else {
throw new RuntimeException("不支持的Word文档格式");
}
} catch (IOException e) {
throw new RuntimeException("无法读取Word文档", e);
}
}
private static String processOldWordDocument(MultipartFile file) throws IOException {
try (HWPFDocument document = new HWPFDocument(file.getInputStream())) {
WordExtractor extractor = new WordExtractor(document);
String text = extractor.getText();
log.info("Word文档内容: {}", text);
return text;
}
}
private static String processNewWordDocument(MultipartFile file) throws IOException {
try (XWPFDocument document = new XWPFDocument(file.getInputStream())) {
if (document.getParagraphs().isEmpty()) {
throw new RuntimeException("Word文档为空");
}
XWPFWordExtractor extractor = new XWPFWordExtractor(document);
String text = extractor.getText();
log.info("Word文档内容: {}", text);
return text;
}
}
}