技术开发 频道

Office文件格式突变,促使Java和Office更完美集成



    一但上面的事情做完后,必须创建一个ZIP文件,这时我们将使用ZipOutputStream类。由于我们只是变化了document.xml中的内容,其他的xml文件将被直接复制进来,如字体、格式以及其他的东西。做到这一点也非常简单,只要使用ZipEntry对每一个实体进行扫描即可。代码如下:

@Test public void modifyDocumentAndSave() throws Exception { ZipFile docxFile =new ZipFile(new File("test.docx")); ZipEntry documentXML = docxFile.getEntry("word/document.xml"); InputStream documentXMLIS = docxFile.getInputStream(documentXML); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); Document doc = dbf.newDocumentBuilder().parse(documentXMLIS); Element docElement = doc.getDocumentElement(); assertEquals("w:document", docElement.getTagName()); Element bodyElement = (Element) docElement.getElementsByTagName("w:body").item(0); assertEquals("w:body", bodyElement.getTagName()); Element pElement = (Element) bodyElement.getElementsByTagName("w:p").item(0); assertEquals("w:p", pElement.getTagName()); Element rElement = (Element) pElement.getElementsByTagName("w:r").item(0); assertEquals("w:r", rElement.getTagName()); Element tElement = (Element) rElement.getElementsByTagName("w:t").item(0); assertEquals("w:t", tElement.getTagName()); assertEquals("这是第一个测试文档", tElement.getTextContent()); tElement.setTextContent( "这是第一个用Java写的测试文档"); Transformer t = TransformerFactory.newInstance().newTransformer(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); t.transform(new DOMSource(doc), new StreamResult(baos)); ZipOutputStream docxOutFile = new ZipOutputStream( new FileOutputStream("response.docx")); Enumeration entriesIter = docxFile.entries(); while (entriesIter.hasMoreElements()) { ZipEntry entry = entriesIter.nextElement(); if(entry.getName().equals("word/document.xml")) { byte[] data = baos.toByteArray(); docxOutFile.putNextEntry(new ZipEntry(entry.getName())); docxOutFile.write(data, 0, data.length); docxOutFile.closeEntry(); } else { InputStream incoming = docxFile.getInputStream(entry); byte[] data = new byte[1024 * 16]; int readCount = incoming.read(data, 0, data.length); docxOutFile.putNextEntry( new ZipEntry(entry.getName())); docxOutFile.write(data, 0, readCount); docxOutFile.closeEntry(); } } docxOutFile.close(); }
 3是上面代码写完后的word2007文档:


    上面的代码演示了如何使用Java的标准库来读写Word2007文档,同样,使用Java也可以读取Excel2007的相应的文档(.xlsx)。这样在使用Java生成Excel报表时就无需使用第三方的库,也不需要调用Excel2007。但在客户端必须安装Excel2007,这也许是一个不足的地方,但随着微软的Office2007系列软件的普及,我相信这将会使我们的报表家族更丰富多彩。
0
相关文章