使用Java将DOC文件转换为DOCX

10

我需要在目前正在开发的Java软件中使用DOCX文件(实际上是其中包含的XML),但公司中有些人仍在使用DOC格式。

您知道是否有一种使用Java将DOC文件转换为DOCX格式的方法吗?我知道使用C#可以实现,但这不是一个选项。

我搜索了一下谷歌,但没有找到任何结果......

谢谢


2
Apache POI 可能会对您完成此任务有所帮助。 - Sorceror
7个回答

3
您可以尝试使用Aspose.Words for Java。它允许您加载DOC文件并将其保存为DOCX格式。代码非常简单,如下所示:
// Open a document.  
Document doc = new Document("input.doc"); 
// Save document. 
doc.save("output.docx");

请看这是否有助于您的情况。
披露:我在Aspose担任开发者传道人。

文档 doc = 新文档(“MyDir” + “in.doc”); 在我的Java页面中使用上述代码时,显示“未定义构造函数Document(String)”并且使用此代码 ------------> doc.save(“output.docx”); 显示为“类型文档的方法save(String)未定义”我是否需要导入任何jar文件。 如果需要,请列出jar文件。 - geetha
我该如何尝试这个?我需要使用哪个依赖项? - Rajesh
@Rajesh,请在您的项目中下载并添加Aspose.Words for Java库,以便使用Java将DOC转换为DOCX和许多其他格式。 您还可以直接从基于Maven的项目中使用Aspose.Words for Java。 如需更多详细信息,请参阅文档。声明:我是Aspose的开发者推广员。 - Awais Hafeez

2

请查看JODConverter,看它是否符合要求。我个人没有使用过。


1
它似乎可以将MSOffice文件转换为OpenOffice格式,但无法将DOC转换为DOCX。不管怎样,谢谢。 - 3rgo

1

请使用更新版本的jar包jodconverter-core-4.2.2.jarjodconverter-local-4.2.2.jar

String inputFile = "*.doc";
String outputFile = "*.docx";

LocalOfficeManager localOfficeManager = LocalOfficeManager.builder()
            .install()
            .officeHome(getDefaultOfficeHome()) //your path to openoffice
            .build();

  try {
      localOfficeManager.start();
      final DocumentFormat format
              = DocumentFormat.builder()
                      .from(DefaultDocumentFormatRegistry.DOCX)
                      .build();

      LocalConverter
              .make()
              .convert(new FileInputStream(new File(inputFile)))
              .as(DefaultDocumentFormatRegistry.getFormatByMediaType("application/msword"))
              .to(new File(outputFile))
              .as(format)
              .execute();

  } catch (OfficeException ex) {
      Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
  } catch (FileNotFoundException ex) {
      Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
  } finally {
      OfficeUtils.stopQuietly(localOfficeManager);
  }

0

我需要进行相同的转换,经过大量研究后发现Jodconvertor可能会有用,您可以从https://code.google.com/p/jodconverter/downloads/list下载jar文件。

将jodconverter-core-3.0-beta-4-sources.jar文件添加到您的项目库中。

  //1) Create OfficeManger Object     
OfficeManager officeManager = new DefaultOfficeManagerConfiguration()
                .setOfficeHome(new File("/opt/libreoffice4.4"))
                .buildOfficeManager();
        officeManager.start();
    // 2) Create JODConverter converter   
        OfficeDocumentConverter converter = new OfficeDocumentConverter(
                officeManager);
// 3)Create DocumentFormat for docx
DocumentFormat docx = converter.getFormatRegistry().getFormatByExtension("docx");
        docx.setStoreProperties(DocumentFamily.TEXT,
                Collections.singletonMap("FilterName", "MS Word 2007 XML"));
//4)Call convert funtion in converter object
converter.convert(new File("doc/AdvancedTable.doc"), new File(
                "docx/AdvancedTable.docx"), docx);

0
JODConvertor通过网络协议调用OpenOffice/LibreOffice。因此,它可以“做任何你在OpenOffice中能做的事情”,包括转换格式。但是,它只能像你运行的OpenOffice版本一样好地完成工作。我有一些艺术品在我的文档中,它们并没有按照我希望的那样进行转换。
根据v3的Google Code网站,JODConvertor已不再受支持。
要让JOD完成你需要做的工作,你需要做类似以下的事情:
private static void transformBinaryWordDocToDocX(File in, File out)
{
    OfficeDocumentConverter converter = new OfficeDocumentConverter(officeManager);
    DocumentFormat docx = converter.getFormatRegistry().getFormatByExtension("docx");
    docx.setStoreProperties(DocumentFamily.TEXT,
    Collections.singletonMap("FilterName", "MS Word 2007 XML"));

    converter.convert(in, out, docx);
}


private static void transformBinaryWordDocToW2003Xml(File in, File out)
{
    OfficeDocumentConverter converter = new OfficeDocumentConverter(officeManager);;
    DocumentFormat w2003xml = new DocumentFormat("Microsoft Word 2003 XML", "xml", "text/xml");
    w2003xml.setInputFamily(DocumentFamily.TEXT);
    w2003xml.setStoreProperties(DocumentFamily.TEXT, Collections.singletonMap("FilterName", "MS Word 2003 XML"));
    converter.convert(in, out, w2003xml);
}



private static OfficeManager officeManager;

@BeforeClass
public static void setupStatic() throws IOException {

          /*officeManager = new DefaultOfficeManagerConfiguration()
      .setOfficeHome("C:/Program Files/LibreOffice 3.6")
      .buildOfficeManager();
      */

    officeManager = new ExternalOfficeManagerConfiguration().setConnectOnStart(true).setPortNumber(8100).buildOfficeManager();


    officeManager.start();
}

@AfterClass
public static void shutdownStatic() throws IOException {

    officeManager.stop();
}

为使其正常工作,您需要将LibreOffice作为网络服务器运行(我无法让JODConvertor的“按需运行”部分在Windows上与LO 3.6良好地配合使用)。


这段代码是否使用OO在无界面模式下将DOC转换为DOCX? - Jalal Sordo

-1

如果要将DOC文件转换为HTML,请查看此链接(在Java中以编程方式将Word文档转换为HTML)

使用这个:http://poi.apache.org/

或者使用这个:

XWPFDocument docx = new XWPFDocument(OPCPackage.openOrCreate(new File("hello.docx")));  
XWPFWordExtractor wx = new XWPFWordExtractor(docx);  
String text = wx.getText();  
System.out.println("text = "+text); 

如果(DOCX!= HTML && hasNoOtherAnswer())则执行Downvote()-好的,你提到了poi,我不会-1。 - Andreas Dolk
它将为您提供从DOC文件获取数据的功能,您可以直接对其进行操作,而无需将其转换为DOCX。 - Cin Sb Sangpi
我需要使用DOCX文件。这是一个很强的要求,很可能是因为软件已经可以处理DOCX文件,但某些输入仍然是旧的DOC格式。因此,转换为HTML并添加HTML解析器似乎不是一个选项。 - Andreas Dolk
确实...我所有的解析器都已经针对DOCX格式进行设置(使用Open XML)。我没有时间编写HTML或文本文件的解析器,因此提出了我的问题。 - 3rgo

-3
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;

import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfWriter;


import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;

import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;


public class TestCon {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        POIFSFileSystem fs = null;  
        Document document = new Document();

        try {  
            System.out.println("Starting the test");  
            fs = new POIFSFileSystem(new FileInputStream("C:/Users/312845/Desktop/a.doc"));  

            HWPFDocument doc = new HWPFDocument(fs);  
            WordExtractor we = new WordExtractor(doc);  

            OutputStream file = new FileOutputStream(new File("C:/Users/312845/Desktop/test.docx")); 

            System.out.println("Document testing completed");  
        } catch (Exception e) {  
            System.out.println("Exception during test");  
            e.printStackTrace();  
        } finally {  
            // close the document  
            document.close();  
        }  
    }  
}

2
仅提供代码的答案在这里不被接受。请解释您所做的事情以及它如何回答他的问题。 - Paul Lemarchand

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接