从模板创建新文档

时间:2016-09-29 12:10:20

标签: java ms-word apache-poi word-template

我想从我的Java-App中的MS-Word模板中打开一个新文档,但只能设法编辑模板本身。

这是我的情况: 在我的Jar文件中是一个单词模板,它被复制到用户指定的位置,因此他/她可以编辑它。之后,应用程序可以打开此编辑的模板,将数据插入其中并用文字打开。这一切都很好(使用Apache-POI),但最后一步并不完全是我想要的。

通常,双击单词模板时,Word会打开一个尚未保存的新文档(标题为Document1)。在我的例子中,Word打开用于编辑的单词模板(标题为blablaMyTemplate),这意味着应该从中创建文档的已保存模板。如何使用Java从模板中打开新创建的文档?

这是我的代码(省略了try / catch和流关闭):

    File bbb = new File(new File(getClass().getProtectionDomain().getCodeSource().getLocation().toURI().getPath()).getParentFile().getParentFile().getAbsolutePath() + "/blablaMyTemplate.dotx");
    if (!bbb.exists()) { //copy file to outside of jar for user editing
        Files.copy(Buchungsbegleitblatt.class.getResourceAsStream("bbb.dotx"), bbb.toPath(), StandardCopyOption.REPLACE_EXISTING);
    }
    File tmp = File.createTempFile("bbb", ".dotx"); //create tmp file to insert data
    InputStream in = new FileInputStream(bbb);
    OutputStream out = new FileOutputStream(tmp);
    XWPFDocument document = new XWPFDocument(in);
    //here, some data is filled into the document using Apache-POI (omitted, because it works fine)
    document.write(out);
    if (Desktop.isDesktopSupported()) {
        Desktop.getDesktop().open(tmp); //this opens the template for editing, it does not create a new doc from template
    }

问题出在最后一行,但我不知道我还能在这里打电话。

为了使它更清晰一点,这里是我在模板文件中获得的上下文菜单的图像以及应该发生的事情:

context menu on template

2 个答案:

答案 0 :(得分:2)

您已经准确地描述了这个问题。 Desktop.open将完全按照其说法行事。它将为被调用的应用程序执行open事件,该事件被分配给文件类型。

您需要执行new事件。这可以使用startup command-line switches to start WordWord中实现。

在链接的知识库条目中,您可以找到:

  

...

     

/ttemplate_name Starts Word with a new document based on a template other than the Normal template.

     

...

Java执行此操作,可以使用Runtime.getRuntime().execProcessBuilder。我建议首先将命令解释器CMD作为shell启动,并使用此命令start启动应用程序。因此,我们无需知道应用程序的确切路径。

示例:

import java.io.*;

class RuntimeExec {
  public static void main(String[] args) {
      try {
        // Execute a command as a single line
        File f = new File("C:/Users/axel/Documents/The Template.dotx");
        System.out.println(f.getAbsolutePath());
        String cmd = "cmd /C start winword.exe /t\"" + f.getAbsolutePath() + "\"";
        Process child = Runtime.getRuntime().exec(cmd);

      } catch (IOException e) {
        e.printStackTrace();
      }

  }
}

class UseProcessBuilder {
  public static void main(String[] args) {
      try {
        //use ProcessBuilder to have more control
        File f = new File("C:/Users/axel/Documents/The Template.dotx");
        System.out.println(f.getAbsolutePath());
        String application = "winword.exe";
        String switchNewFromTemplate = "/t";
        String file = f.getAbsolutePath(); 
        ProcessBuilder pb = new ProcessBuilder("cmd", "/C", "start", application, switchNewFromTemplate+file);
        Process process = pb.start();

      } catch (IOException e) {
        e.printStackTrace();
      }
  }
}

有一种可能性没有明确启动winword应用程序。如果我们将空字符串start作为应用程序名称,""命令具有根据给定文件的文件扩展名执行默认操作的功能:

start "" "The name of the file.ext"

示例:

start "" "The name of the file.dotx"

这将在new应用程序中执行与注册表数据库中winword扩展名相关的默认操作dotx

所以:

class RuntimeExec {
  public static void main(String[] args) {
      try {
        // Execute a command as a single line
        File f = new File("C:/Users/Axel Richter/Documents/The Template.dotx");
        System.out.println(f.getAbsolutePath());
        String cmd = "cmd /C start \"\" \"" + f.getAbsolutePath() + "\"";
        Process child = Runtime.getRuntime().exec(cmd);

        InputStream in = child.getErrorStream();
        int c;
        while ((c = in.read()) != -1) {
            System.out.print((char)c);
        }
        in.close();

      } catch (IOException e) {
        e.printStackTrace();
      }

  }
}

class UseProcessBuilder {
  public static void main(String[] args) {
      try {
        //use ProcessBuilder to have more control
        File f = new File("C:/Users/Axel Richter/Documents/The Template.dotx");
        System.out.println(f.getAbsolutePath());
        String file = f.getAbsolutePath(); 
        ProcessBuilder pb = new ProcessBuilder("cmd", "/C", "start", "\"\"", file);
        Process process = pb.start();

        InputStream in = process.getErrorStream();
        int c;
        while ((c = in.read()) != -1) {
            System.out.print((char)c);
        }
        in.close();

      } catch (IOException e) {
        e.printStackTrace();
      }
  }
}

答案 1 :(得分:0)

执行此操作的一种方法是在模板上启动进程,以便Windows处理打开,并使用默认意图。自从我接触过Java以来​​已经有一段时间了,但如果它像C#那样会像new Process(tmp).Start()那样。

尽管如此,我并不确定这是否是您正在寻找的,确切地说。