Java利用POI读写word文件

Java利用POI读写word文件

对于word文档的读写等操作是大多数开发者都会遇到的问题。Apache的POI是解决word读写的方案之一。本文展示的是通过HWPFDocument读写文件。

一、读取word内容

 

public class HwpfTest {  
    public static void hwpfRead() throws IOException {
        File file = new File("C:\\Users\\Desktop\\test.doc");
        String doc1 = "";
        String doc2 = "";
        try {
            FileInputStream is= new FileInputStream(file);
            HWPFDocument doc = new HWPFDocument(is);
            String doc1 = doc.getDocumentText();
            System.out.println(doc1);
            Range rang = doc.getRange();
            String doc2 = rang.text();
            System.out.println(doc2);
            this.closeStream(is);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 /** 
    * 关闭输入流 
    * @param is 
    */  
   private void closeStream(InputStream is) {  
      if (is != null) {  
         try {  
            is.close();  
         } catch (IOException e) {  
            e.printStackTrace();  
         }  
      }  
   }
}

 二、向word文件写入内容

      在使用POIword doc文件的时候我们必须要先有一个doc文件才行,因为我们在写doc文件的时候是通过HWPFDocument来写的,而HWPFDocument是要依附于一个doc文件的。

      在实际开发中,我们在生成word文件的时候都是生成某一类文件,该类文件的格式是固定的,只是某些字段不一样罢了。所以在实际应用中,我们大可不必将整个word文件的内容都通过HWPFDocument生成。而是先在磁盘上新建一个word文档,其内容就是我们需要生成的word文件的内容,然后把里面一些属于变量的内容使用类似于“${paramName}”这样的方式代替。这样我们在基于某些信息生成word文件的时候,只需要获取基于该word文件的HWPFDocument,然后调用RangereplaceText()方法把对应的变量替换为对应的值即可,之后再把当前的HWPFDocument写入到新的输出流中。

public class HwpfWriteTest {  
    
   public void testWrite() throws Exception {  
      String templatePath = "C:\\User\\Desktop\\template.doc";  
      InputStream is = new FileInputStream(templatePath);  
      HWPFDocument doc = new HWPFDocument(is);  
      Range range = doc.getRange();  
      //将文档中的"${helloword}"替换为"Hi"
      range.replaceText("${helloword}", "Hi");  
      OutputStream os = new FileOutputStream("C:\\User\\Desktop\\write.doc");  
      //把doc输出到输出流中  
      doc.write(os);  
      this.closeStream(os);  
      this.closeStream(is);  
   }  
    
   /** 
    * 关闭输入流 
    * @param is 
    */  
   private void closeStream(InputStream is) {  
      if (is != null) {  
         try {  
            is.close();  
         } catch (IOException e) {  
            e.printStackTrace();  
         }  
      }  
   }  
   
   /** 
    * 关闭输出流 
    * @param os 
    */  
   private void closeStream(OutputStream os) {  
      if (os != null) {  
         try {  
            os.close();  
         } catch (IOException e) {  
            e.printStackTrace();  
         }  
      }  
   }  
    
   
}  

 

 

猜你喜欢

转载自1395573703.iteye.com/blog/2357938