POI读写WORD的docx文件,指定位置插入表格或者图片,生成新的WORD文件

临时给项目组写的一个操作word2007的示例程序;

开发环境是windows,使用的POI版本是3.14

通过word文件模板,可替换模板中变量,同时可以在指定位置插入表格或者图片,生成新的WORD文件;

 

 

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

import java.util.Map.Entry;

import org.apache.poi.POIXMLDocument;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;

import org.apache.poi.openxml4j.opc.OPCPackage;

import org.apache.poi.util.Units;

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

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

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;

 

import org.apache.xmlbeans.XmlCursor;

 

public class WordUtil2007 {

 

/**

* 根据指定的参数值、模板,生成 word 文档

* @param param

*            需要替换的变量

* @param template

*            模板

*/

public static XWPFDocument generateWord(Map param,

String template) {

CustomXWPFDocument doc = null;

try {

OPCPackage pack = POIXMLDocument.openPackage(template);

doc = new CustomXWPFDocument(pack);

if (param != null && param.size() > 0) {

 

// 处理段落

List paragraphList = doc.getParagraphs();

processParagraphs(paragraphList, param, doc);

 

}

} catch (Exception e) {

e.printStackTrace();

}

return doc;

}

 

/**

* 处理段落中文本,替换文本中定义的变量;

* @param paragraphList

*            段落列表

* @param param

*            需要替换的变量及变量值

* @param doc

*            需要替换的DOC

*/

public static void processParagraphs(List paragraphList,

Map param, XWPFDocument doc) {

if (paragraphList != null && paragraphList.size() > 0) {

for (XWPFParagraph paragraph : paragraphList) {

List runs = paragraph.getRuns();

for (XWPFRun run : runs) {

String text = run.getText(0);

if (text != null) {

boolean isSetText = false;

for (Entry entry : param.entrySet()) {

String key = entry.getKey();

if (text.indexOf(key) != -1) {

isSetText = true;

Object value = entry.getValue();

if (value instanceof String) {// 文本替换

text = text.replace(key, value.toString());

}

}

}

if (isSetText) {

run.setText(text, 0);

}

}

}

}

}

}

 

/**

* 在定位的位置插入表格;

* @param key

*            定位的变量值

* @param doc

*            需要替换的DOC

*/

 

public static void insertTab(String key, XWPFDocument doc2) {

 

List paragraphList = doc2.getParagraphs();

if (paragraphList != null && paragraphList.size() > 0) {

 

for (XWPFParagraph paragraph : paragraphList) {

List runs = paragraph.getRuns();

 

for (XWPFRun run : runs) {

String text = run.getText(0);

 

if (text != null) {

if (text.indexOf(key) >= 0) {

 

XmlCursor cursor = paragraph.getCTP().newCursor();

 

XWPFTable tableOne = doc2.insertNewTbl(cursor);// ---这个是关键

 

// XWPFTable tableOne =

// paragraph.getDocument().createTable();

 

XWPFTableRow tableOneRowOne = tableOne.getRow(0);

tableOneRowOne.getCell(0).setText("一行一列");

XWPFTableCell cell12 = tableOneRowOne.createCell();

cell12.setText("一行二列");

// tableOneRowOne.addNewTableCell().setText("第1行第2列");

// tableOneRowOne.addNewTableCell().setText("第1行第3列");

// tableOneRowOne.addNewTableCell().setText("第1行第4列");

 

XWPFTableRow tableOneRowTwo = tableOne.createRow();

tableOneRowTwo.getCell(0).setText("第二行第一列");

tableOneRowTwo.getCell(1).setText("第二行第二列");

// tableOneRowTwo.getCell(2).setText("第2行第3列");

 

XWPFTableRow tableOneRow3 = tableOne.createRow();

//---顺序增加行后,忽略第1、2单元格,直接插入3、4

tableOneRow3.addNewTableCell().setText("第三行第3列");

tableOneRow3.addNewTableCell().setText("第三行第4列");

 

}

}

}

 

}

}

}

 

public static void insertImage(String key, XWPFDocument doc) {

 

List paragraphList = doc.getParagraphs();

 

try {

 

if (paragraphList != null && paragraphList.size() > 0) {

 

for (XWPFParagraph paragraph : paragraphList) {

List runs = paragraph.getRuns();

 

for (XWPFRun run : runs) {

String text = run.getText(0);

 

if (text != null) {

if (text.indexOf(key) >= 0) {

 

run.addBreak();

run.addPicture(

new FileInputStream("c:/11.jpg"),Document.PICTURE_TYPE_JPEG,"c:/11.jpg", Units.toEMU(200),Units.toEMU(200)); // 200x200 pixels

run.addBreak(BreakType.PAGE);

 

}

}

}

 

}

}

 

} catch (InvalidFormatException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (FileNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

 

}

 

 

 

 

/**

* 测试用方法

*/

 

public static void main(String[] args) throws Exception {

 

Map param = new HashMap();

param.put("${name}", "哈哈哈哈");

param.put("${zhuanye}", "信息管理与信息系统");

param.put("${sex}", "男");

param.put("${school}", "大学");

param.put("${date}", "2016-09-21");

 

Map twocode = new HashMap();

twocode.put("width", 100);

twocode.put("height", 100);

twocode.put("type", "png");

 

XWPFDocument doc = WordUtil2007.generateWord(param, "d:\\2007.docx");

 

WordUtil2007.insertTab("${table}", doc); // /----------创建表

WordUtil2007.insertImage("${image}", doc); // /----------创建图

 

// ------替换多余的标志位----//

 

param = new HashMap();

param.put("${test}", "下一个段落");

param.put("${table}", "");

param.put("${image}", "");

 

WordUtil2007.processParagraphs(doc.getParagraphs(), param, doc);

 

FileOutputStream fopts = new FileOutputStream("d:\\2007-2.docx");

doc.write(fopts);

 

}

}

 

你可能感兴趣的:(POI)