welcome to xlongwei.com

欢迎大家一起学习、交流、分享


QQ:9167702333 邮箱:admin@xlongwei.com

WordUtil 读取word模板文件,填充数据并写入文档


分类 Java   关键字 分享   标签 java   algorithm   发布 hongwei  1440121783456
注意 转载须保留原文链接,译文链接,作者译者等信息。  
按照word模板文件填充数据并下载还是挺有用的,下载的word文件可以编辑(填写信息等),如果想要下载的文档不可编辑则使用pdf文件下载即可。
  • HWPFDocument read(File source),读取模板文件,HWPFDocument是poi对word的封装对象
  • replace(HWPFDocument doc, Map<String, String> replaces),替换部分文字
  • table(HWPFDocument doc, int index, List<Map<String, String>> data),处理第几张表格
  • tables(HWPFDocument doc, List<List<Map<String, String>>> tables),处理全部表格
  • Map<String, String> row(String... cols),封装表格一行的数据
    List<Map<String, String>> table(Map<String, String>... rows),封装单张表格数据
    List<List<Map<String, String>>> tables(List<Map<String, String>>... tables),封装全部表格数据
  • boolean write(HWPFDocument doc, File target),写入word文档

package com.itecheast.ite.front.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.IOUtils;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.hwpf.usermodel.Table;
import org.apache.poi.hwpf.usermodel.TableIterator;
import org.apache.poi.hwpf.usermodel.TableRow;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class WordUtil {
private static Logger logger = LoggerFactory.getLogger(WordUtil.class);

public static HWPFDocument read(File source) {
InputStream is = null;
try {
HWPFDocument doc = new HWPFDocument(
is = new FileInputStream(source));
logger.info("read doc file: " + source);
return doc;
} catch (IOException e) {
logger.warn("fail to read doc file: " + source.getAbsolutePath(), e);
return null;
} finally {
IOUtils.closeQuietly(is);
}
}

public static boolean write(HWPFDocument doc, File target) {
OutputStream os = null;
try {
doc.write(os = new FileOutputStream(target));
logger.info("write doc to file: " + target);
return true;
} catch (IOException e) {
logger.warn("fail to write doc to file: " + target, e);
return false;
} finally {
IOUtils.closeQuietly(os);
}
}

public static boolean replace(HWPFDocument doc, Map<String, String> replaces) {
if (replaces != null && replaces.size() > 0) {
Range range = doc.getRange();
for (String key : replaces.keySet()) {
String value = replaces.get(key);
// key = "${"+key+"}"; //optional
range.replaceText(key, value);
}
logger.info("replace doc file ok");
return true;
}else {
logger.info("nothing to replace cause of empty replaces");
return false;
}
}

public static boolean table(HWPFDocument doc, int index,
List<Map<String, String>> data) {
Range range = doc.getRange();
TableIterator tableIterator = new TableIterator(range);

int tableIndex = 0;
Table table = null;
while (tableIterator.hasNext()) {
tableIndex++;
table = tableIterator.next();
if (tableIndex == index) {
break;
}
}
if (tableIndex == index) {
table(table, data);
logger.info("table doc file ok, index: " + index);
} else {
logger.warn("fail to find table of index: " + index);
}
return true;
}

public static boolean tables(HWPFDocument doc,
List<List<Map<String, String>>> tables) {
if (tables != null && tables.size() > 0) {
Range range = doc.getRange();
TableIterator tableIterator = new TableIterator(range);
Iterator<List<Map<String, String>>> dataIterator = tables
.iterator();
while (tableIterator.hasNext() && dataIterator.hasNext()) {
Table table = tableIterator.next();
List<Map<String, String>> data = dataIterator.next();

table(table, data);
logger.info("table doc file ok");
}
if (tableIterator.hasNext()) {
logger.warn("more table left with no data");
} else if (dataIterator.hasNext()) {
logger.warn("less table than data blocks");
}
logger.info("tables doc file ok");
return true;
} else {
logger.info("nothing to tables cause of empty tables");
return false;
}
}

private static void table(Table table, List<Map<String, String>> data) {
int rows = table.numRows();
for (int r = 0; r < rows - 1; r++) {
TableRow tr = table.getRow(r + 1);// first row is title
Map<String, String> map = data.size() > r ? data.get(r) : null;
if (map != null) {
for (String key : map.keySet()) {
String value = map.get(key);
tr.replaceText(key, value);
}
} else {
tr.delete(); // remove empty rows
logger.debug("table row removed");
}
}
if (data.size() > rows) {
for (int r = rows; r < data.size(); r++) {
// how to insert row ?
logger.info("how to insert row: " + r);
}
}
}

public static Map<String, String> row(String... cols) {
Map<String, String> row = new HashMap<>();
for (int i = 0; i < cols.length; i += 2) {
row.put(cols[i], cols[i + 1]);
}
return row;
}
@SuppressWarnings("unchecked")
public static List<Map<String, String>> table(Map<String, String>... rows) {
List<Map<String, String>> table = new LinkedList<>();
for (Map<String, String> row : rows) {
table.add(row);
}
return table;
}

@SuppressWarnings("unchecked")
public static List<List<Map<String, String>>> tables(
List<Map<String, String>>... tables) {
List<List<Map<String, String>>> content = new LinkedList<>();
for (List<Map<String, String>> table : tables) {
content.add(table);
}
return content;
}
}