利用Java读取并写入Word文件

本文介绍了一个Java程序示例,该程序可以读取和修改Word文档的内容。通过使用Apache POI库,程序能够替换文档中的占位符文本,并将更新后的文档保存到指定位置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

利用Java读取并写入Word文件

标签: javaword文档
  11206人阅读  评论(5)  收藏  举报
  分类:
 
[java]  view plain  copy
  1. /* 
  2.  * 文 件 名:  MSWordPoi4.<a href="http://lib.youkuaiyun.com/base/17" class="replace_word" title="Java EE知识库" target="_blank" style="color:#df3434; font-weight:bold;">java</a> 
  3.  * 版    权:  Sunny Technologies Co., Ltd. Copyright YYYY-YYYY,  All rights reserved 
  4.  * 描    述:  <描述> 
  5.  * 修 改 人:  L.Hao 
  6.  * 修改时间:  2014-8-8 
  7.  * 跟踪单号:  <跟踪单号> 
  8.  * 修改单号:  <修改单号> 
  9.  * 修改内容:  <修改内容> 
  10.  */  
  11. package com.test;  
  12.   
  13. /** 
  14.  * <一句话功能简述> 
  15.  * <功能详细描述> 
  16.  *  
  17.  * @author  L.Hao 
  18.  * @version  [版本号, 2014-8-8] 
  19.  * @see  [相关类/方法] 
  20.  * @since  [产品/模块版本] 
  21.  */  
  22. import java.io.ByteArrayOutputStream;  
  23. import java.io.File;  
  24. import java.io.FileInputStream;  
  25. import java.io.FileNotFoundException;  
  26. import java.io.FileOutputStream;  
  27. import java.io.IOException;  
  28. import java.util.HashMap;  
  29. import java.util.Iterator;  
  30. import java.util.Map;  
  31.   
  32. import org.apache.poi.hwpf.HWPFDocument;  
  33. import org.apache.poi.hwpf.model.FieldsDocumentPart;  
  34. import org.apache.poi.hwpf.usermodel.Field;  
  35. import org.apache.poi.hwpf.usermodel.Fields;  
  36. import org.apache.poi.hwpf.usermodel.Paragraph;  
  37. import org.apache.poi.hwpf.usermodel.Range;  
  38. import org.apache.poi.hwpf.usermodel.Table;  
  39. import org.apache.poi.hwpf.usermodel.TableCell;  
  40. import org.apache.poi.hwpf.usermodel.TableIterator;  
  41. import org.apache.poi.hwpf.usermodel.TableRow;  
  42.   
  43. public class MSWordPoi4  
  44. {  
  45.       
  46.     /** 
  47.     * @param args 
  48.     */  
  49.     public static void main(String[] args)  
  50.     {  
  51.         Map<String, String> map = new HashMap<String, String>();  
  52.         map.put("${sub}""湖南大学");  
  53.         map.put("${item2.school}""湖南大学");  
  54.         map.put("${item2.address}""湖南");  
  55. //        map.put("${item1.name}", "王五1");  
  56. //        map.put("${item1.numberStudent}", "编号002");  
  57. //        map.put("${item1.sex}", "男2");  
  58. //        map.put("${item1.age}", "19");  
  59.         String srcPath = "D:\\temp\\铸造工艺卡.doc";  
  60.         readwriteWord(srcPath, map);  
  61.     }  
  62.       
  63.     /** 
  64.     * 实现对word读取和修改操作 
  65.     *  
  66.     * @param filePath 
  67.     *            word模板路径和名称 
  68.     * @param map 
  69.     *            待填充的数据,从<a href="http://lib.youkuaiyun.com/base/14" class="replace_word" title="MySQL知识库" target="_blank" style="color:#df3434; font-weight:bold;">数据库</a>读取 
  70.     */  
  71.     public static void readwriteWord(String filePath, Map<String, String> map)  
  72.     {  
  73.         // 读取word模板  
  74.         // String fileDir = new  
  75.         // File(base.getFile(),"http://www.cnblogs.com/http://www.cnblogs.com/../doc/").getCanonicalPath();  
  76.         FileInputStream in = null;  
  77.         try  
  78.         {  
  79.             in = new FileInputStream(new File(filePath));  
  80.         }  
  81.         catch (FileNotFoundException e1)  
  82.         {  
  83.             e1.printStackTrace();  
  84.         }  
  85.         HWPFDocument hdt = null;  
  86.         try  
  87.         {  
  88.             hdt = new HWPFDocument(in);  
  89.         }  
  90.         catch (IOException e1)  
  91.         {  
  92.             e1.printStackTrace();  
  93.         }  
  94.         Fields fields = hdt.getFields();  
  95.         Iterator<Field> it = fields.getFields(FieldsDocumentPart.MAIN)  
  96.                 .iterator();  
  97.         while (it.hasNext())  
  98.         {  
  99.             System.out.println(it.next().getType());  
  100.         }  
  101.           
  102.         //读取word文本内容  
  103.         Range range = hdt.getRange();  
  104.         TableIterator tableIt = new TableIterator(range);   
  105.         //迭代文档中的表格  
  106.         int ii = 0;  
  107.         while (tableIt.hasNext()) {    
  108.             Table tb = (Table) tableIt.next();    
  109.             ii++;  
  110.             System.out.println("第"+ii+"个表格数据...................");  
  111.             //迭代行,默认从0开始  
  112.             for (int i = 0; i < tb.numRows(); i++) {    
  113.                 TableRow tr = tb.getRow(i);    
  114.                 //只读前8行,标题部分  
  115.                 if(i >=8break;  
  116.                 //迭代列,默认从0开始  
  117.                 for (int j = 0; j < tr.numCells(); j++) {    
  118.                     TableCell td = tr.getCell(j);//取得单元格  
  119.                     //取得单元格的内容  
  120.                     for(int k=0;k<td.numParagraphs();k++){    
  121.                         Paragraph para =td.getParagraph(k);    
  122.                         String s = para.text();    
  123.                         System.out.println(s);  
  124.                     } //end for     
  125.                 }   //end for  
  126.             }   //end for  
  127.         } //end while  
  128.         //System.out.println(range.text());  
  129.           
  130.         // 替换文本内容  
  131.         for (Map.Entry<String, String> entry : map.entrySet())  
  132.         {  
  133.             range.replaceText(entry.getKey(), entry.getValue());  
  134.         }  
  135.         ByteArrayOutputStream ostream = new ByteArrayOutputStream();  
  136.         String fileName = "" + System.currentTimeMillis();  
  137.         fileName += ".doc";  
  138.         FileOutputStream out = null;  
  139.         try  
  140.         {  
  141.             out = new FileOutputStream("F:/" + fileName, true);  
  142.         }  
  143.         catch (FileNotFoundException e)  
  144.         {  
  145.             e.printStackTrace();  
  146.         }  
  147.         try  
  148.         {  
  149.             hdt.write(ostream);  
  150.         }  
  151.         catch (IOException e)  
  152.         {  
  153.             e.printStackTrace();  
  154.         }  
  155.         // 输出字节流  
  156.         try  
  157.         {  
  158.             out.write(ostream.toByteArray());  
  159.         }  
  160.         catch (IOException e)  
  161.         {  
  162.             e.printStackTrace();  
  163.         }  
  164.         try  
  165.         {  
  166.             out.close();  
  167.         }  
  168.         catch (IOException e)  
  169.         {  
  170.             e.printStackTrace();  
  171.         }  
  172.         try  
  173.         {  
  174.             ostream.close();  
  175.         }  
  176.         catch (IOException e)  
  177.         {  
  178.             e.printStackTrace();  
  179.         }  
  180.     }  
  181. }  

所使用到的jar是:


2
1
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值