使用Java读取Word文件的简单例子分享

时间:2021-12-11 10:27:34

java读取word文档时,虽然网上介绍了很多插件poi、java2Word、jacob、itext等等,poi无法读取格式(新的API估计行好像还在处于研发阶段,不太稳定,做项目不太敢用);java2Word、jacob容易报错找不到注册,比较诡异,我曾经在不同的机器上试过,操作方法完全一致,有的机器不报错,有的报错,去他们论坛找高人解决也说不出原因,项目部署用它有点玄;itxt好像写很方便但是我查了好久资料没有见到过关于读的好办法。经过一番选择还是折中点采用rtf最好,毕竟rtf是开源格式,不需要借助任何插件,只需基本IO操作外加编码转换即可。rtf格式文件表面看来和doc没啥区别,都可以用word打开,各种格式都可以设定。
 
----- 实现的功能:读取rtf模板内容(格式和文本内容),替换变化部分,形成新的rtf文档。
 
----- 实现思路:模板中固定部分手动输入,变化的部分用$info$表示,只需替换$info$即可。
 
       1、采用字节的形式读取rtf模板内容
       2、将可变的内容字符串转为rtf编码
       3、替换原文中的可变部分,形成新的rtf文档
 
主要程序如下:
 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
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("源模板文件不存在");
     }
     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("读取模板文件结束");
        break;
       }
       sourcecontent += new String(b, 0, bytesRead); // convert to string using bytes
      }
 }catch(Exception e){
  e.printStackTrace();
 }
 return sourcecontent ;
}

   
      以上为核心代码,剩余部分就是替换,从新组装java中的String.replace(oldstr,newstr);方法可以实现,在这就不贴了。源代码部分详见附件。
运行源代码前提:
c盘创建YQ目录,将附件中"模板.rtf"复制到YQ目录之下,运行OpreatorRTF.java文件即可,就会在YQ目录下生成文件名如:21时15分19秒_cheney_记录.rtf 的文件。 
 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
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".toCharArray();
 
    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(replacecontent);
 
       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] == 32){
 
          c[i] = (char) 12288;
 
          continue;
 
        }
 
        if (c[i] < 127){
 
           c[i] = (char) (c[i] + 65248);
 
        }
 
      }
 
      return 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) + "时";
 
       targetname += sdf.format(current).substring(14,16) + "分";
 
       targetname += sdf.format(current).substring(17,19) + "秒";
 
       targetname += "_" + username +"_记录.rtf";
 
            
       String strpath = getSavePath();
 
       String sourname = strpath+"\\"+"模板.rtf";
 
       String sourcecontent = "";
 
       InputStream ins = null;
 
       try{
 
           ins = new FileInputStream(sourname);
 
           byte[] b = new byte[1024];
 
        if (ins == null) {
 
           System.out.println("源模板文件不存在");
 
        }
 
        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("读取模板文件结束");
 
              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(sourcecontent, array[i], i);
 
           }else{
 
              targetcontent = replaceRTF(targetcontent, array[i], i);
 
           }         
 
       
 
       
       try {
 
           FileWriter fw = new FileWriter(getSavePath()+"\\" + targetname,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()+" 该目录下生成文件" + targetname + " 成功");
 
       } 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 = "2008年10月12日9时-2008年10月12日6时~我们参照检验药品的方法~我们参照检验药品的方法~我们参照检验药品的方法~我们参照检验药品的方法";
 
       oRTF.rgModel("cheney",content);
 
    }
 
}


使用POI读取word文件的表格数据的示例:
使用Java读取Word文件的简单例子分享

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
<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>