Java实现DOC转DOCX的完整解决方案(Apache POI)
https://comate.baidu.com/zh/page/fzefys8i7e0?xml version1.0 encodingUTF-8? project xmlnshttp://maven.apache.org/POM/4.0.0 xmlns:xsihttp://www.w3.org/2001/XMLSchema-instance xsi:schemaLocationhttp://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd modelVersion4.0.0/modelVersion groupIdcom.example/groupId artifactIddoc-to-docx/artifactId version1.0-SNAPSHOT/version properties maven.compiler.source11/maven.compiler.source maven.compiler.target11/maven.compiler.target /properties dependencies dependency groupIdorg.apache.poi/groupId artifactIdpoi/artifactId version5.2.3/version /dependency dependency groupIdorg.apache.poi/groupId artifactIdpoi-scratchpad/artifactId version5.2.3/version /dependency dependency groupIdorg.apache.poi/groupId artifactIdpoi-ooxml/artifactId version5.2.3/version /dependency /dependencies build plugins plugin groupIdorg.codehaus.mojo/groupId artifactIdexec-maven-plugin/artifactId version3.1.0/version configuration mainClasscom.example.DocToDocxConverter/mainClass /configuration /plugin /plugins /build /projectpackage com.example; import org.apache.poi.hwpf.HWPFDocument; import org.apache.poi.hwpf.usermodel.Paragraph; import org.apache.poi.hwpf.usermodel.Range; import org.apache.poi.xwpf.usermodel.*; import java.io.*; public class DocToDocxConverter { public static void main(String[] args) { if (args.length ! 2) { System.out.println(Usage: java DocToDocxConverter input.doc output.docx); return; } String inputPath args[0]; String outputPath args[1]; try { convertDocToDocx(inputPath, outputPath); System.out.println(Conversion completed successfully!); } catch (Exception e) { System.err.println(Error during conversion: e.getMessage()); e.printStackTrace(); } } public static void convertDocToDocx(String inputPath, String outputPath) throws IOException { try (InputStream docStream new FileInputStream(inputPath); HWPFDocument doc new HWPFDocument(docStream); XWPFDocument docx new XWPFDocument(); FileOutputStream out new FileOutputStream(outputPath)) { Range range doc.getRange(); for (int i 0; i range.numParagraphs(); i) { Paragraph paragraph range.getParagraph(i); if (paragraph.text().trim().isEmpty()) continue; XWPFParagraph xwpfParagraph docx.createParagraph(); XWPFRun run xwpfParagraph.createRun(); run.setText(paragraph.text()); // 基础格式保留 if (paragraph.isInList()) { xwpfParagraph.setSpacingAfter(100); } } docx.write(out); } } }
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2422761.html
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!