1.pom
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.12</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>3.12</version>
</dependency>
2.代码
package com.knife.tjava;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.ParagraphAlignment;
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.openxmlformats.schemas.wordprocessingml.x2006.main.CTBorder;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRPr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblBorders;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STBorder;
/**
* Hello world!
*
*/
public class App
{
public static void addBorders(XWPFTable table) {
CTTblBorders borders = table.getCTTbl().getTblPr().addNewTblBorders();
CTBorder hBorder = borders.addNewInsideH();
hBorder.setVal(STBorder.Enum.forString("single"));
hBorder.setSz(new BigInteger("1"));
hBorder.setColor("000000");
CTBorder vBorder = borders.addNewInsideV();
vBorder.setVal(STBorder.Enum.forString("single"));
vBorder.setSz(new BigInteger("1"));
vBorder.setColor("000000");
CTBorder lBorder = borders.addNewLeft();
lBorder.setVal(STBorder.Enum.forString("single"));
lBorder.setSz(new BigInteger("1"));
lBorder.setColor("000000");
CTBorder rBorder = borders.addNewRight();
rBorder.setVal(STBorder.Enum.forString("single"));
rBorder.setSz(new BigInteger("1"));
rBorder.setColor("000000");
CTBorder tBorder = borders.addNewTop();
tBorder.setVal(STBorder.Enum.forString("single"));
tBorder.setSz(new BigInteger("1"));
tBorder.setColor("000000");
CTBorder bBorder = borders.addNewBottom();
bBorder.setVal(STBorder.Enum.forString("single"));
bBorder.setSz(new BigInteger("1"));
bBorder.setColor("000000");
}
/**
* 插入图片
*
* @param paragraph
* @param is
* @throws IOException
* @throws InvalidFormatException
*/
public static void addPic(XWPFParagraph paragraph, InputStream is) throws IOException, InvalidFormatException {
XWPFRun run = paragraph.createRun();
run.setBold(true);
paragraph.setAlignment(ParagraphAlignment.CENTER);
run.addBreak();
run.addPicture(is, XWPFDocument.PICTURE_TYPE_PNG, "", Units.toEMU(200), Units.toEMU(200)); // 200x200 pixels
is.close();
}
public static XWPFDocument openDocument(String saveFile) {
XWPFDocument xdoc = null;
InputStream is = null;
try {
is = new FileInputStream(saveFile);
xdoc = new XWPFDocument(is);
} catch (IOException e) {
e.printStackTrace();
}
return xdoc;
}
public static void initTables(Map<String, Object> map, List<XWPFTable> tables) {
System.out.println("########### tables:");
for (XWPFTable table : tables) {
String sign = "";
if (table.getRows().size() == 1) {
sign = table.getRow(0).getCell(0).getText();
sign = sign.replace("${@", "").replace("}", "");
System.out.println(sign);
if (map.get(sign) != null) {
table.getRow(0).getCell(0).removeParagraph(0);
String[][] arr = (String[][]) map.get(sign);
for (int i = 0; i < arr.length; i++) {
XWPFTableRow row = table.getRow(i);
if (row == null) {
row = table.createRow();
}
for (int j = 0; j < arr[i].length; j++) {
XWPFTableCell cell = row.getCell(j);
if (cell == null) {
cell = row.createCell();
}
cell.setText(arr[i][j]);
}
}
} else {
table.removeRow(0);
}
} else if (table.getRows().size() == 2) {
sign = table.getRow(1).getCell(0).getText();
sign = sign.replace("${@", "").replace("}", "");
System.out.println(sign);
if (map.get(sign) != null) {
table.getRow(1).getCell(0).removeParagraph(0);
addBorders(table);
String[][] arr = (String[][]) map.get(sign);
for (int i = 0; i < arr.length; i++) {
XWPFTableRow row = table.getRow(i + 2);
if (row == null) {
row = table.insertNewTableRow(i + 2);
// row.getCtRow().setTrPr(table.getRow(1).getCtRow().getTrPr());
row.getCtRow().addNewTrPr();
}
for (int j = 0; j < arr[i].length; j++) {
XWPFTableCell cell = row.getCell(j);
if (cell == null) {
//System.out.println("###############create new cell");
cell = row.createCell();
// cell.getCTTc().setTcPr(table.getRow(1).getCell(j).getCTTc().getTcPr());
cell.getCTTc().addNewTcPr();
}
cell.setText(arr[i][j]);
}
}
}
table.removeRow(1);
}
}
}
public static void initImage(Map<String, Object> map, List<XWPFParagraph> paragraphs) {
System.out.println("#########image:");
for (XWPFParagraph paragraph : paragraphs) {
String text = paragraph.getText();
if (text.startsWith("#{")) {
String sign = text.replace("#{", "").replace("}", "");
System.out.println(sign);
paragraph.removeRun(0);
if (map.containsKey(sign) && map.get(sign) != null) {
try {
//addPic(paragraph, encryptToInputStreamFromSvg(map.get("svgcode").toString()));
addPic(paragraph, (InputStream) map.get(sign));
} catch (InvalidFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
public static void initParagraphs(Map<String, Object> map, List<XWPFParagraph> paragraphs) {
System.out.println("#########paragraphs:");
for (XWPFParagraph paragraph : paragraphs) {
String text = paragraph.getText();
if (text.startsWith("${")) {
if (!text.startsWith("${@")) {
String sign = text.replace("${", "").replace("}", "");
System.out.println(sign);
if (map.get(sign) != null) {
CTRPr pr = paragraph.getRuns().get(0).getCTR().getRPr();
XWPFRun run = paragraph.createRun();
run.setText(map.get(text.replace("${", "").replace("}", "")).toString());
run.getCTR().setRPr(pr);
}
} else {
String sign = text.replace("${@", "").replace("}", "");
System.out.println(sign);
if (map.containsKey(sign)) {
String[] arr = (String[]) map.get(sign);
CTRPr pr = paragraph.getRuns().get(0).getCTR().getRPr();
for (String str : arr) {
XWPFRun run = paragraph.createRun();
run.setText(str + "\r\n");
run.getCTR().setRPr(pr);
}
}
}
paragraph.removeRun(0);
}
}
}
public static XWPFDocument export(Map<String, Object> map, String modelpath) {
XWPFDocument doc = openDocument(modelpath);
List<XWPFParagraph> paragraphs = doc.getParagraphs();
List<XWPFTable> tables = doc.getTables();
initParagraphs(map, paragraphs);
initImage(map, paragraphs);
initTables(map, tables);
return doc;
}
public static void export(File file, Map<String, Object> map, String modelpath) {
XWPFDocument doc = export(map, modelpath);
FileOutputStream fos = null;
try {
// File file = new File("D://testdoc.docx");
fos = new FileOutputStream(file);
doc.write(fos);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public static void main(String args[]) throws FileNotFoundException {
Map<String, Object> map = new HashMap<String, Object>();
map.put("string1", "这是第一个段落");
map.put("string2", new String[] { "循环1", "循环2", "循环3" });
map.put("table1", new String[][] { { "1", "加藤一刀斋", "15", "廊桥之町" } });
map.put("table2", new String[][] { { "输入", "角色", "kpi", "输出" }, { "输入1", "角色", "kpi", "输出" },
{ "输入2", "角色", "kpi", "输出" } });
map.put("image1", new FileInputStream(new File("D://1.png")));
export(new File("D://testExport.docx"), map, "D://testModel.docx");
}
}
3.模板
4.导出结果