简体   繁体   English

用Java编写Word文档

[英]Writing a word document in Java

I'm trying to write the output Strings into a word document using the following code : 我正在尝试使用以下代码将输出字符串写入Word文档:

 try {
          out = new PrintWriter(new BufferedWriter(new FileWriter("report.doc", true)));
          out.println("<html><style>"+string1+"</style><table cellspacing = 0 cellpadding = 0><tr>" + string2 + "</html>" +  (char)12);
      } catch (IOException e) {
          JOptionPane.showMessageDialog(null,  "File error " + e.getMessage());
      } finally {
          if (out != null) {
              try {
                  out.close();
              } catch (Exception ignore) {
              }
          }
      }

If this method is called (let's say) 10 times, it only writes the information of the first String. 如果此方法被调用了10次(比如说),它只会写入第一个String的信息。 However, when I replace 'report.doc' with 'report.html', the created html file contains all the information of the 10 Strings. 但是,当我用“ report.html”替换“ report.doc”时,创建的html文件包含10个字符串的所有信息。

How can I alter my code so that it can generate a word document with all the information as is the created html document? 如何更改代码,以便它可以像生成的html文档一样生成包含所有信息的word文档?

You need to use a .doc processor java library. 您需要使用.doc处理器Java库。 Without the help of word processor library, you need to know the format of .doc documents, just you know the structure of .html documents. 没有文字处理程序库的帮助,您仅需要了解.html文档的结构,就需要了解.doc文档的格式。

Apache poi is a good example of such a library. Apache poi是此类库的一个很好的例子。

Another approach is to port the MS Office libraries to a java library using COM bridges. 另一种方法是使用COM桥将MS Office库移植到Java库。 I have been using a commercial tool for that purpose. 为此,我一直在使用商业工具。 JACOB seems an open source example of a Java-COM bridge, though I have not tested this product. 尽管我尚未测试该产品,但JACOB似乎是Java-COM桥的开源示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM