Java实现doc文件和docx文件互转的几种方式
方式1:利用aspose进行转换
Jar包地址:
链接:https://pan.baidu.com/s/1pwJ-gwghInoU-_M60ZF_YQ
提取码:3eek
// 将doc输入流转换为docx输入流
private static InputStream convertDocIs2DocxIs(InputStream docInputStream) throws IOException {
byte[] docBytes = FileCopyUtils.copyToByteArray(docInputStream);
byte[] docxBytes = convertDocStream2docxStream(docBytes);
return new ByteArrayInputStream(docxBytes);
}
// 将doc字节数组转换为docx字节数组
private static byte[] convertDocStream2docxStream(byte[] arrays) {
byte[] docxBytes = new byte[1];
if (arrays != null && arrays.length > 0) {
try (
ByteArrayOutputStream os = new ByteArrayOutputStream();
InputStream sbs = new ByteArrayInputStream(arrays)
) {
com.aspose.words.Document doc = new com.aspose.words.Document(sbs);
doc.save(os, SaveFormat.DOCX);
docxBytes = os.toByteArray();
} catch (Exception e) {
System.out.println("出错啦");
}
}
return docxBytes;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
备注:该方式同样可以实现将docx转换为doc文件,只需指定SaveFormat的格式。
方式2:spire.doc.free
首先导入依赖
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.doc.free</artifactId>
<version>3.9.0</version>
</dependency>
- 1
- 2
- 3
- 4
- 5
代码:
Document document = new Document();
document.loadFromFile("源文件路径");
document.saveToFile("目标文件的路径", FileFormat.Docx);
- 1
- 2
- 3
方式3:同样可以使用JodConverter转换
jod可以实现多种文档之间的相互转换,具体案例百度上有很多。
方式4:利用documents4j实现
首先是依赖
<dependency>
<groupId>com.documents4j</groupId>
<artifactId>documents4j-local</artifactId>
<version>1.0.3</version>
</dependency>
<dependency>
<groupId>com.documents4j</groupId>
<artifactId>documents4j-transformer-msoffice-word</artifactId>
<version>1.0.3</version>
</dependency>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
示例代码:
public static void convert(String fileType) {
File inputWord = new File("D:\\test_workspace\\testdemo\\src\\main\\resources\\targetFile.docx");
File outputFile = new File("D:\\zzz.doc");
try (InputStream docxInputStream = new FileInputStream(inputWord);
OutputStream outputStream = new FileOutputStream(outputFile)) {
IConverter converter = LocalConverter.builder().build();
boolean flag = false;
if("docx".equals(fileType)){// docx转doc
flag = converter.convert(docxInputStream).as(DocumentType.DOCX).to(outputStream).as(DocumentType.DOC).execute();
} else if ("doc".equals(fileType)){ //
flag = converter.convert(docxInputStream).as(DocumentType.DOC).to(outputStream).as(DocumentType.PDF).execute();
}
if (flag) {
converter.shutDown();
}
System.out.println("转换成功");
} catch (Exception e) {
e.printStackTrace();
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
备注:有人说linux下documents4j转换会出现异常,具体没有去验证。