andrid 读取Word文件 (无格式)

来源:互联网 发布:铃声助手mac版 编辑:程序博客网 时间:2024/06/06 03:38

需要额JAR包

package other.a;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;

import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.model.FieldsDocumentPart;
import org.apache.poi.hwpf.usermodel.Field;
import org.apache.poi.hwpf.usermodel.Fields;
import org.apache.poi.hwpf.usermodel.Range;

public class Test2 {

 public static void main(String[] args) {

  try { 
   // 读取word模板
   String fileDir = new File("../../../../../YQ/").getCanonicalPath(); 
   FileInputStream in = new FileInputStream(new File(fileDir
     + "/模板.doc"));
   HWPFDocument hdt = new HWPFDocument(in);
   Fields fields = hdt.getFields();
   Iterator<Field> it = fields.getFields(FieldsDocumentPart.MAIN)
     .iterator();
   while (it.hasNext()) {
    System.out.println(it.next().getType());
   }

   // 读取word文本内容
   Range range = hdt.getRange();
   System.out.println(range.text());
   // 替换文本内容
   // for (Map.Entry<String,String> entry:map.entrySet()) {
   // range.replaceText(entry.getKey(),entry.getValue());
   // }
   ByteArrayOutputStream ostream = new ByteArrayOutputStream();
   String fileName = "" + System.currentTimeMillis();
   fileName += ".doc";
   FileOutputStream out = new FileOutputStream(fileDir + "/"
     + fileName, true);
   hdt.write(ostream);
   
   out.write(ostream.toByteArray());
   out.close();
   ostream.close();
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
}