【Java】通过java将doc文件转换为docx
在Java中,可以使用Apache POI库将.doc文件转换为.docx文件。以下是一个简单的示例代码,展示了如何实现这一转换:
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Range;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class DocToDocxConverter {
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("input.doc"); // 替换为你的.doc文件路径
HWPFDocument document = new HWPFDocument(fis);
Range range = document.getRange();
// 创建一个新的docx文档
XWPFDocument newDocument = new XWPFDocument();
// 转换文档的段落
for (int i = 0; i < range.numParagraphs(); i++) {
XWPFParagraph paragraph = newDocument.createParagraph();
paragraph.createRun().setText(range.getParagraph(i).text());
}
// 写入新的.docx文件
FileOutputStream out = new FileOutputStream("output.docx"); // 替换为你想要的.docx文件路径
newDocument.write(out);
out.close();
newDocument.close();
fis.close();
}
}
确保在执行此代码之前,你的项目中已经添加了Apache POI依赖。如果没有,你可以通过Maven添加:
<dependencies>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>5.2.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
评论已关闭