简体   繁体   中英

Writing a word document in Java

I'm trying to write the output Strings into a word document using the following code :

 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. However, when I replace 'report.doc' with 'report.html', the created html file contains all the information of the 10 Strings.

How can I alter my code so that it can generate a word document with all the information as is the created html document?

You need to use a .doc processor java library. Without the help of word processor library, you need to know the format of .doc documents, just you know the structure of .html documents.

Apache poi is a good example of such a library.

Another approach is to port the MS Office libraries to a java library using COM bridges. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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