A simple example of using Java to read a Word file share _java

Source: Internet
Author: User
Tags stub stringbuffer

Java when reading Word documents, although many plug-ins on the web are introduced POI, Java2word, Jacob, Itext, and so on, POI unreadable format (the new API estimate line seems to be in the research and development phase, not too stable, do not dare to use the project); Java2word, Jacob Easy to complain can not find registration, more bizarre, I have tried in different machines, operation method is completely consistent, some machines do not complain, some errors, go to their forum to find an expert solution also said no reason, the project deployment with it a bit Hyun iTXt seems to be very convenient to write, but I have been looking for a long time the information has not seen a good way to read. After some choice or compromise point using RTF is the best, after all, RTF is open source format, do not need to use any plug-ins, just basic IO operation plus code conversion can be. Rich Text Format file on the surface and Doc does not make any difference, can be opened in Word, various formats can be set. The
 
-----Implements the ability to read rich-text template content (formatting and textual content), replace the change section, and form a new RTF document.
&NBSP
-----Implementation: The fixed part of the template is manually entered, the changed part is represented by $info$, just replace the $info$.
 
       1, Reading RTF template content in bytes
       2, Converts a variable content string to RTF
       3, replaces the variable part in the original text, and forms a new RTF document
 
Main program is as follows:
 

public string Bin2Hex (String bin) {char[] digital = "0123456789ABCDEF". ToCharArray ();
    StringBuffer sb = new StringBuffer ("");
    byte[] bs = Bin.getbytes ();
    int bit;
 
      for (int i = 0; i < bs.length;i++) {bit = (Bs[i] & 0x0f0) >> 4;
      Sb.append ("\ \");
      Sb.append (Digital[bit]);
      bit = Bs[i] & 0x0f;
    Sb.append (Digital[bit]);
  return sb.tostring ();
 public string Readbytertf (InputStream ins, string path) {string sourcecontent = "";
  try{ins = new FileInputStream (path);
     Byte[] B = new byte[1024];
     if (INS = null) {System.out.println ("source template file does not exist");
     int bytesread = 0; while (true) {bytesread = Ins.read (b, 0, 1024);//return final Read bytes counts if (bytesread = = 1) {//E
        nd of InputStream System.out.println ("Read template file End");
       Break } sourcecontent + = new String (b, 0, bytesread); Convert to string using bytes}}catch (Exception E) {e.printstacktrace ();
return sourcecontent;
 }

&NBSP;&NBSP;&NBSP
      above is the core code, and the remainder is replaced by the new assembly of String.Replace in Java (oldstr,newstr The method can be implemented and is not posted here. The Source code section is detailed in the attachment.
Run Source code Prerequisites:
C disk to create the YQ directory, the Attachment "template. rtf" copied to the Yq directory, run the Opreatorrtf.java file, you will be in the YQ directory generated file name such as: 21:15 19 seconds _cheney_ record. rtf of the file. &NBSP
 

Package com;
Import Java.io.File;
Import Java.io.FileInputStream;
Import Java.io.FileWriter;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.PrintWriter;
Import Java.text.SimpleDateFormat;
 
 
Import Java.util.Date; public class Operatorrtf {public string strtortf (string content) {char[] digital = "0123456789ABCDEF". Toch
 
    Ararray ();
 
    StringBuffer sb = new StringBuffer ("");
 
    byte[] bs = Content.getbytes ();
 
    int bit;
 
        for (int i = 0; i < bs.length i++) {bit = (Bs[i] & 0x0f0) >> 4;
 
      Sb.append ("\ \");
 
      Sb.append (Digital[bit]);
 
      bit = Bs[i] & 0x0f;
 
    Sb.append (Digital[bit]);
 
    return sb.tostring (); public string Replacertf (string content,string replacecontent,int flag) {String rc = Strtortf (replacecont
 
       ENT);
 
       
 
       String target = "";
 
       if (flag==0) {target = Content.replace ("$timetop $", RC); } IF (flag==1) {target = Content.replace ("$info $", RC);
 
       } if (flag==2) {target = Content.replace ("$idea $", RC);
 
       } if (flag==3) {target = Content.replace ("$advice $", RC);
 
       } if (flag==4) {target = Content.replace ("$infosend $", RC);
 
    return target;
 
       
 
       public string Getsavepath () {String path = ' C:\\yq ';
 
       File Fdirecotry = new file (path);
 
       if (!fdirecotry.exists ()) {fdirecotry.mkdirs ();
 
    return path;
 
      public string TOSBC (string input) {char[] c = Input.tochararray ();
 
          for (int i = 0; i < c.length i++) {if (c[i] = =) {C[i] = (char) 12288;
 
        Continue
 
        } if (C[i] < 127) {C[i] = (char) (C[i] + 65248);
 
    Return the new String (c); } public void Rgmodel (StrinG username, String content) {//TODO auto-generated method Stub date Current=new date ();
 
       SimpleDateFormat sdf=new Java.text.SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss");
 
       String targetname = Sdf.format (current). substring (11,13) + "Time";
 
       TargetName + = Sdf.format (current). substring (14,16) + "min";
 
       TargetName + = Sdf.format (current). substring (17,19) + "seconds";
 
            
       TargetName + = "_" + Username + "_ record. rtf";
 
       String strpath = Getsavepath ();
 
       String sourname = strpath+ "\" + "template. rtf";
 
       String sourcecontent = "";
 
       InputStream ins = null;
 
           try{ins = new FileInputStream (sourname);
 
        Byte[] B = new byte[1024];
 
        if (INS = null) {System.out.println ("source template file does not exist");
 
        int bytesread = 0;  while (true) {bytesread = Ins.read (b, 0, 1024);//return final Read bytes counts if (bytesread = = -1) {//End of INPUTSTReam System.out.println ("Read template file End");
 
          Break } sourcecontent + = new String (b, 0, bytesread);
 
       Convert to string using bytes}}catch (Exception e) {e.printstacktrace ();
       
 
       } String targetcontent = "";
             
 
       String array[] = Content.split ("~"); for (int i=0;i<array.length;i++) {if (i==0) {targetcontent = Replacertf (sourcec
 
           Ontent, Array[i], i);
 
           }else{targetcontent = replacertf (Targetcontent, array[i], i); The try {FileWriter fw = new FileWriter (Getsavepath () + "\" + Targetnam
 
      E,true);
 
      PrintWriter out = new PrintWriter (FW); if (Targetcontent.equals ("") | |
 
      targetcontent== "") {out.println (sourcecontent);
 
      }else{out.println (targetcontent);
 
} out.close ();      Fw.close ();
 
       System.out.println (Getsavepath () + "The directory generated file" + TargetName + "success");
 
       catch (IOException e) {//TODO auto-generated catch block E.printstacktrace (); } public static void Main (string[] args) {//TODO auto-generated method stub operatorrtf
       
       ORTF = new Operatorrtf ();
 
       String content = "October 12, 2008 9 o'clock-October 12, 2008 6 o'clock ~" We refer to the method of testing drugs ~ we refer to the method of testing drugs ~ we refer to the method of testing drugs ~ we refer to the method of testing drugs;
 
    Ortf.rgmodel ("Cheney", content);
 }

}


Example of using POI to read tabular data for a Word file:

<span style= "FONT-SIZE:14PX;" 
 
>package Com.poi.world; 
 
Import Java.io.FileInputStream; 
Import org.apache.poi.hwpf.HWPFDocument; 
Import Org.apache.poi.hwpf.usermodel.Paragraph; 
Import Org.apache.poi.hwpf.usermodel.Range; 
Import org.apache.poi.hwpf.usermodel.Table; 
Import Org.apache.poi.hwpf.usermodel.TableCell; 
Import Org.apache.poi.hwpf.usermodel.TableIterator; 
Import Org.apache.poi.hwpf.usermodel.TableRow; 
 
Import Org.apache.poi.poifs.filesystem.POIFSFileSystem; 
      public class poi_word{public static void Main (string[] args) {try {string[] s=new string[20]; 
      FileInputStream in=new FileInputStream ("D:\\mayi.doc"); 
      Poifsfilesystem pfs=new Poifsfilesystem (in); 
      Hwpfdocument hwpf=new hwpfdocument (PFS); 
      Range range =hwpf.getrange (); 
      Tableiterator it=new tableiterator (range); 
      int index=0; 
        while (It.hasnext ()) {Table tb= (table) It.next (); for (int i=0;i<tb.numrows (); i++) {//system.ouT.println ("NumRows:" +tb.numrows ()); 
          TableRow Tr=tb.getrow (i); 
for (int j=0;j<tr.numcells (); j + +) {//system.out.println ("Numcells:" +tr.numcells ()); 
            System.out.println ("J:" +j); 
            TableCell Td=tr.getcell (j); 
              for (int k=0;k<td.numparagraphs (); k++) {//system.out.println ("numparagraphs:" +td.numparagraphs ()); 
               Paragraph Para=td.getparagraph (k); 
               S[index]=para.text (). Trim (); 
            index++; 
      }}}//System.out.println (s.tostring ()); 
      for (int i=0;i<s.length;i++) {System.out.println (s[i]); 
    } catch (Exception e) {e.printstacktrace (); 
 }}}</span>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.