poi 处理 word

环境:使用maven依赖,直接导入jar文件

一. poi处理word

    maven依赖:

               word3依赖包                 

    <dependency >
             <groupId> org.apache.poi</groupId >
             <artifactId>poi-scratchpad</artifactId>
             <version>3.10-FINAL</version >
       </dependency>

        word7依赖包

    <dependency>
             <groupId> org.apache.poi</groupId >
             <artifactId>poi-ooxml</artifactId>
             <version>3.10-FINAL</version >
       </dependency>

   注意:我们使用word模板时会通过类似 ${value}$ 变量注入值, 但在这里请不要用中文。XWPFDocument分割的XWPFRun会把中文和特殊符号$ 分割成多个XWPFRun; 如果是中文, 请删掉整个 "$中文$", 换成 "$chinese$"。

处理word工具类:

package com.xmgit.word;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.xwpf.usermodel.BodyElementType;
import org.apache.poi.xwpf.usermodel.IBodyElement;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;

public class PoiWordUtil {

	/**
	 * 2007word 模板文字替换 比较2003word复杂,主要注意在字符串分割时 可能会把${year} 变量分割成多个部分(不要填中文);因此
	 * 需保证 模板文件该变量 能分割成单一一个
	 * @param map
	 * @param templatePath
	 * @return
	 */
	public static XWPFDocument replaceWordIn2007(Map<String,String> map, String templatePath){
		try {
			XWPFDocument document = new XWPFDocument(new FileInputStream(templatePath));
			List<IBodyElement> elements = document.getBodyElements();
			for(IBodyElement element : elements){
				if(element.getElementType() == BodyElementType.PARAGRAPH){
					XWPFParagraph para = (XWPFParagraph)element;
					for(XWPFRun run : para.getRuns()){
						String rstr = run.getText(0);
						if(rstr == null){
							continue;
						}
						Iterator<Entry<String, String>> iterator = map.entrySet().iterator();
						while(iterator.hasNext()){
							Entry<String, String> entry = iterator.next();
							String key = entry.getKey();
							String value = entry.getValue();
							if(rstr.contains(key)){
								rstr = rstr.replace(key, value);
								run.setText(rstr,0);
							}
						}
					}
				}
				else if(element.getElementType() == BodyElementType.TABLE){
					XWPFTable table = (XWPFTable)element;
					List<XWPFTableRow> rows = table.getRows();
					for(XWPFTableRow row : rows){
						for(XWPFTableCell cell : row.getTableCells()){
							for(XWPFParagraph para : cell.getParagraphs()){
								List<XWPFRun> runs = para.getRuns();
								for(XWPFRun run : runs){
									String rstr = run.getText(0);
									if(rstr == null){
										continue;
									}
									
									Iterator<Entry<String, String>> iterator = map.entrySet().iterator();
									while(iterator.hasNext()){
										Entry<String, String> entry = iterator.next();
										String key = entry.getKey();
										String value = entry.getValue();
										if(rstr.contains(key)){
											rstr = rstr.replace(key, value);
											run.setText(rstr,0);
										}
									}
								}
							}
						}
					}
				}
			}
			return document;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 2003word 模板 变量直接替换变量
	 * @param map
	 * @param templatePath
	 * @return
	 */
	public static HWPFDocument replaceWordIn2003(Map<String,String> map, String templatePath){
		HWPFDocument document = null;
		try {
			document = new HWPFDocument(new FileInputStream(templatePath));
			Range range = document.getRange();
			Iterator<Entry<String, String>> iterator = map.entrySet().iterator();
			while(iterator.hasNext()){
				Entry<String, String> entry = iterator.next();
				String key = entry.getKey();
				String value = entry.getValue();
				range.replaceText(key, value);
			}
			return document;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
}

2003word处理:

package com.xmgit.word;

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.poi.hwpf.HWPFDocument;

public class Word2003 {

	/**
	 * word3 处理
	 * @param args
	 */
	public static void main(String[] args) {
		ByteArrayOutputStream ostream = null;
		FileOutputStream out = null;
		try{
			Map<String, String> map = new HashMap<String, String>();
			map.put("$设备名称$", "2014");
			map.put("${name}", "蓓蓓");
			map.put("${age}", "27");
			
			String path = Word2007.class.getClassLoader().getResource("").getPath()+"设备台账登记卡.doc";
			HWPFDocument document = PoiWordUtil.replaceWordIn2003(map, path);
			
			ostream = new ByteArrayOutputStream();
			out = new FileOutputStream("C:/Documents and Settings/jsun/桌面/"+System.currentTimeMillis()+".doc",true);
			document.write(ostream);
			out.write(ostream.toByteArray());
			out.close();
			ostream.close();
		
		} catch (Exception e) {
			e.printStackTrace();
		}  
		finally{
			if(ostream != null){
				try {
					if(ostream != null){
						ostream.close();
					}
					if(out != null){
						out.close();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

}

2007 word处理:

package com.xmgit.word;

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.poi.xwpf.usermodel.XWPFDocument;

public class Word2007 {

	
	public static void main(String[] args) {
		ByteArrayOutputStream ostream = null;
		FileOutputStream out = null;
		try{
			Map<String, String> map = new HashMap<String, String>();
			map.put("${year}", "2014");
			map.put("${name}", "蓓蓓");
			map.put("${age}", "27");
			
			String path = Word2007.class.getClassLoader().getResource("").getPath()+"2007word.docx";
			XWPFDocument document = PoiWordUtil.replaceWordIn2007(map, path);
			
			ostream = new ByteArrayOutputStream();
			out = new FileOutputStream("C:/Documents and Settings/jsun/桌面/"+System.currentTimeMillis()+".doc",true);
			document.write(ostream);
			out.write(ostream.toByteArray());
			out.close();
			ostream.close();
		
		} catch (Exception e) {
			e.printStackTrace();
		}  
		finally{
			if(ostream != null){
				try {
					if(ostream != null){
						ostream.close();
					}
					if(out != null){
						out.close();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
       
	}

}


转载于:https://my.oschina.net/u/590281/blog/291909

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值