java实现word文档doc和docx两种格式互转
小编今天遇到个问题,正如标题所说的。百度了好久,没有突破,还是在最后,有了希望!!!
直接附上代码
- /*** doc 格式 */
- private static final int DOC_FMT = 0;
- /*** docx 格式 */
- private static final int DOCX_FMT = 12;
- public static void main(String[] args) {
- DocFmtConvert dfc = new DocFmtConvert();
- String srcDocPath = "D:/test.doc";
- String descDocPath = "D:/test.docx";
- try {
- dfc.convertDocFmt(srcDocPath, descDocPath, DOCX_FMT);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- /**
- * 根据格式类型转换 word 文件
- *
- * @param srcPath 源文件
- * @param descPath 目标文件
- * @param fmt 所转格式
- */
- public File convertDocFmt(String srcPath, String descPath, int fmt) throws Exception {
- // 实例化ComThread线程与ActiveXComponent
- ComThread.InitSTA();
- ActiveXComponent app = new ActiveXComponent("Word.Application");
- try {
- // 文档隐藏时进行应用操作
- app.setProperty("Visible", new Variant(false));
- // 实例化模板Document对象
- Dispatch document = app.getProperty("Documents").toDispatch();
- // 打开Document进行另存为操作
- Dispatch doc = Dispatch.invoke(document, "Open", Dispatch.Method, new Object[] { srcPath, new Variant(true), new Variant(true) }, new int[1]).toDispatch();
- Dispatch.invoke(doc, "SaveAs", Dispatch.Method, new Object[] { descPath, new Variant(fmt) }, new int[1]);
- Dispatch.call(doc, "Close", new Variant(false));
- return new File(descPath);
- } catch (Exception e) {
- throw e;
- } finally {
- // 释放线程与ActiveXComponent
- app.invoke("Quit", new Variant[] {});
- ComThread.Release();
- }
- }
以上代码需要正常运行需要 jacob 的支持
下载完成之后,需要将压缩包中的 jar 文件拷贝到项目中,将 dll 文件拷贝到 C:/windows/system32 下(只能放86的 dll),或者拷贝到当前项目运行的 jdk 的目录下的 jre/bin 目录下
如上图所示,小编的这个项目是用的 jdk7,所以要放到下图所示
放到 jdk/jre/bin 目录下时,需要注意自己电脑是多少位的,放置对应的 dll 文件。
小编为了省事就都放了,这样也不会因为没有找到合适位数的 dll 文件导致程序无法运行了!
以上内容如有问题,还请大神多多指教!!