有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java从模板创建新文档

我想从Java应用程序的MS Word模板中打开一个新文档,但只能编辑模板本身

以下是我的情况: 在我的Jar文件中有一个word模板,它被复制到用户指定的位置,这样他/她就可以编辑它。之后,应用程序可以打开这个编辑过的模板,向其中插入数据,然后在word中打开它。这一切都很好(使用ApachePOI),但最后一步并不是我想要的

通常,双击word模板时,word会打开一个尚未保存在任何位置的新文档(标题为Document1)。在我的例子中,Word打开Word template进行编辑(标题为BlabullyTemplate),这意味着应该从中创建文档的已保存模板。如何使用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


共 (1) 个答案

  1. # 1 楼答案

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

    不过,我不确定这是否正是你想要的