POI动态生成word2007加强版

2023-11-11 04:30

本文主要是介绍POI动态生成word2007加强版,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

先看效果图:


public class GeneralTemplateWord2007Util {

public static void main(String[] args) {
// TODO Auto-generated method stub
String filePath = "C:/Users/Administrator/Desktop/doc/模板.docx";
String outFile = "C:/Users/Administrator/Desktop/生成模板.docx";
Map<String, Object> params = new HashMap<String, Object>();
params.put("font", "你好");
params.put("name", "小宝");
params.put("age", "xx");
params.put("sex", "男");
params.put("job", "肉盾");
params.put("hobby", "电商");
params.put("phone", "1717");
        

try {
GeneralTemplateWord2007Util gt = new GeneralTemplateWord2007Util();

Map<String, List<List<String>>> map=new HashMap<String, List<List<String>>>();
map.put("user", gt.generateTestData(5));
map.put("aa", gt.generateTestData(7));
map.put("mytable", gt.generateTestData(11));

gt.templateWrite(filePath, outFile, params, map);
System.out.println("生成模板成功");
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("生成模板失败");
e.printStackTrace();
}
}


// 生成測试数据
public List<List<String>> generateTestData(int num) {
List<List<String>> resultList = new ArrayList<List<String>>();
for (int i = 1; i <= num; i++) {
List<String> list = new ArrayList<String>();
list.add("" + i);
list.add("測试_" + i);
list.add("測试2_" + i);
list.add("測试3_" + i);
list.add("測试4_" + i);
list.add("測试5_" + i);
resultList.add(list);
}
return resultList;
}


/**
* 用一个docx文档作为模板,然后替换当中的内容,再写入目标文档中。



* @throws Exception
*/
public void templateWrite(String filePath, String outFile,
Map<String, Object> params, Map<String, List<List<String>>> map)
throws Exception {


InputStream is = new FileInputStream(filePath);
XWPFDocument doc = new XWPFDocument(is);
// 替换段落里面的变量
this.replaceInPara(doc, params);
// 替换表格里面的变量并插入数据
this.insertValueToTable(doc, params, map);
OutputStream os = new FileOutputStream(outFile);
doc.write(os);
this.close(os);
this.close(is);
}


/**
* 替换段落里面的变量

* @param doc
*            要替换的文档
* @param params
*            參数
* @throws Exception 
*/
private void replaceInPara(XWPFDocument doc, Map<String, Object> params) throws Exception {
Iterator<XWPFParagraph> iterator = doc.getParagraphsIterator();
XWPFParagraph para;
while (iterator.hasNext()) {
para = iterator.next();
this.replaceInPara(para, params);
}
}


/**
* 替换段落里面的变量

* @param para
*            要替换的段落
* @param params
*            參数
* @throws Exception 
*/
private String replaceInPara(XWPFParagraph para, Map<String, Object> params) throws Exception {
String str=null;
List<XWPFRun> runs;
XWPFRun run = null;
Matcher matcher;
Matcher mr;
int fontSize=0;
boolean setBold=false;
boolean setItalic=false;
UnderlinePatterns setUnderline=null; 
String setColor="";
int setTextPosition=0;
String setFontFamily=null;


if (this.matcher(para.getParagraphText()).find()) {
runs = para.getRuns();
for (int i = 0; i < runs.size(); i++) {
run = runs.get(i);
String runText = run.toString();
matcher = this.matcher(runText);
if (matcher.find()) {
while ((matcher = this.matcher(runText)).find()) {
runText = matcher.replaceFirst(String.valueOf(params
.get(matcher.group(1))));
}
// 直接调用XWPFRun的setText()方法设置文本时,在底层会又一次创建一个XWPFRun。把文本附加在当前文本后面。
// 所以我们不能直接设值。须要先删除当前run,然后再自己手动插入一个新的run。
fontSize=run.getFontSize();
setBold=run.isBold();
setItalic=run.isItalic();
setUnderline=run.getUnderline();
setColor=run.getColor();
setTextPosition=run.getTextPosition();
setFontFamily=run.getFontFamily();

para.removeRun(i);
XWPFRun runP = para.insertNewRun(i);

runP.setText(runText);
runP.setBold(setBold);
runP.setItalic(setItalic);
runP.setUnderline(setUnderline);
runP.setColor(setColor);
runP.setTextPosition(setTextPosition);

if(fontSize!=-1) runP.setFontSize(fontSize);
if (setFontFamily != null) runP.setFontFamily(setFontFamily);
}
}
} else if ((mr=this.matcherRow(para.getParagraphText())).find()) {
str=mr.group(1)+"";
}
return str;
}


/**
* 按模版行样式填充数据,暂未实现特殊样式填充(如列合并),仅仅能用于普通样式(如段落间距 缩进 字体 对齐)

* @param doc
*            要替换的文档
* @param params
*            參数
* @param resultList
*            须要遍历的数据
* @throws Exception
*/
private void insertValueToTable(XWPFDocument doc,
Map<String, Object> params, Map<String, List<List<String>>> map)
throws Exception {
Iterator<XWPFTable> iterator = doc.getTablesIterator();
XWPFTable table = null;
List<XWPFTableRow> rows = null;
List<XWPFParagraph> paras;
List<XWPFTableCell> tmpCells = null;// 模版列
XWPFTableRow tmpRow = null;// 匹配用
XWPFTableCell tmpCell = null;// 匹配用
int thisRow = 0;
String str=null;
while (iterator.hasNext()) {
List<XWPFTableCell> cells = null;
List<List<String>> resultList=null;
table = iterator.next();
rows = table.getRows();
for (int i = 1; i <= rows.size(); i++) {
cells = rows.get(i - 1).getTableCells();
for (XWPFTableCell cell : cells) {
paras = cell.getParagraphs();
for (XWPFParagraph para : paras) {
str=this.replaceInPara(para, params);
if (str!=null) {
thisRow = i;// 找到模板行
resultList=map.get(str);

tmpRow = rows.get(i - 1);
cells = tmpRow.getTableCells();


}
}
}
}
if (thisRow > 0 && resultList.size()>0) {
this.insertRowToTable(table, tmpRow, tmpCell, thisRow,
resultList, tmpCells, tmpCells);
} else {
System.out.println("该表格中未找到动态标志符");
return;
}
thisRow = 0;
}
}


public void insertRowToTable(XWPFTable table, XWPFTableRow tmpRow,
XWPFTableCell tmpCell, int thisRow, List<List<String>> resultList,
List<XWPFTableCell> tmpCells, List<XWPFTableCell> cells)
throws Exception {
tmpCells = tmpRow.getTableCells();
for (int i = 0, len = resultList.size(); i < len; i++) {
XWPFTableRow row = table.insertNewTableRow(thisRow + i);
row.setHeight(tmpRow.getHeight());
List<String> list = resultList.get(i);
cells = row.getTableCells();
// 插入的行会填充与表格第一行同样的列数
for (int k = 0, klen = cells.size(); k < klen; k++) {
tmpCell = tmpCells.get(k);
XWPFTableCell cell = cells.get(k);
setCellText(tmpCell, cell, list.get(k));
}
// 继续写剩余的列
for (int j = cells.size(), jlen = list.size(); j < jlen; j++) {
tmpCell = tmpCells.get(j);
XWPFTableCell cell = row.addNewTableCell();
setCellText(tmpCell, cell, list.get(j));
}
}
// 删除模版行
table.removeRow(thisRow - 1);
}


public void setCellText(XWPFTableCell tmpCell, XWPFTableCell cell,
String text) throws Exception {
CTTc cttc2 = tmpCell.getCTTc();
CTTcPr ctPr2 = cttc2.getTcPr();


CTTc cttc = cell.getCTTc();
CTTcPr ctPr = cttc.addNewTcPr();
cell.setColor(tmpCell.getColor());
// cell.setVerticalAlignment(tmpCell.getVerticalAlignment());
if (ctPr2.getTcW() != null) {
ctPr.addNewTcW().setW(ctPr2.getTcW().getW());
}
if (ctPr2.getVAlign() != null) {
ctPr.addNewVAlign().setVal(ctPr2.getVAlign().getVal());
}
if (cttc2.getPList().size() > 0) {
CTP ctp = cttc2.getPList().get(0);
if (ctp.getPPr() != null) {
if (ctp.getPPr().getJc() != null) {
cttc.getPList().get(0).addNewPPr().addNewJc()
.setVal(ctp.getPPr().getJc().getVal());
}
}
}


if (ctPr2.getTcBorders() != null) {
ctPr.setTcBorders(ctPr2.getTcBorders());
}


XWPFParagraph tmpP = tmpCell.getParagraphs().get(0);
XWPFParagraph cellP = cell.getParagraphs().get(0);
XWPFRun tmpR = null;
if (tmpP.getRuns() != null && tmpP.getRuns().size() > 0) {
tmpR = tmpP.getRuns().get(0);
}
XWPFRun cellR = cellP.createRun();
cellR.setText(text);
// 复制字体信息
if (tmpR != null) {
cellR.setBold(tmpR.isBold());
cellR.setItalic(tmpR.isItalic());
cellR.setStrike(tmpR.isStrike());
cellR.setUnderline(tmpR.getUnderline());
cellR.setColor(tmpR.getColor());
cellR.setTextPosition(tmpR.getTextPosition());
if (tmpR.getFontSize() != -1) {
cellR.setFontSize(tmpR.getFontSize());
}
if (tmpR.getFontFamily() != null) {
cellR.setFontFamily(tmpR.getFontFamily());
}
if (tmpR.getCTR() != null) {
if (tmpR.getCTR().isSetRPr()) {
CTRPr tmpRPr = tmpR.getCTR().getRPr();
if (tmpRPr.isSetRFonts()) {
CTFonts tmpFonts = tmpRPr.getRFonts();
CTRPr cellRPr = cellR.getCTR().isSetRPr() ? cellR
.getCTR().getRPr() : cellR.getCTR().addNewRPr();
CTFonts cellFonts = cellRPr.isSetRFonts() ?

cellRPr
.getRFonts() : cellRPr.addNewRFonts();
cellFonts.setAscii(tmpFonts.getAscii());
cellFonts.setAsciiTheme(tmpFonts.getAsciiTheme());
cellFonts.setCs(tmpFonts.getCs());
cellFonts.setCstheme(tmpFonts.getCstheme());
cellFonts.setEastAsia(tmpFonts.getEastAsia());
cellFonts.setEastAsiaTheme(tmpFonts.getEastAsiaTheme());
cellFonts.setHAnsi(tmpFonts.getHAnsi());
cellFonts.setHAnsiTheme(tmpFonts.getHAnsiTheme());
}
}
}
}
// 复制段落信息
cellP.setAlignment(tmpP.getAlignment());
cellP.setVerticalAlignment(tmpP.getVerticalAlignment());
cellP.setBorderBetween(tmpP.getBorderBetween());
cellP.setBorderBottom(tmpP.getBorderBottom());
cellP.setBorderLeft(tmpP.getBorderLeft());
cellP.setBorderRight(tmpP.getBorderRight());
cellP.setBorderTop(tmpP.getBorderTop());
cellP.setPageBreak(tmpP.isPageBreak());
if (tmpP.getCTP() != null) {
if (tmpP.getCTP().getPPr() != null) {
CTPPr tmpPPr = tmpP.getCTP().getPPr();
CTPPr cellPPr = cellP.getCTP().getPPr() != null ?

cellP
.getCTP().getPPr() : cellP.getCTP().addNewPPr();
// 复制段落间距信息
CTSpacing tmpSpacing = tmpPPr.getSpacing();
if (tmpSpacing != null) {
CTSpacing cellSpacing = cellPPr.getSpacing() != null ? cellPPr
.getSpacing() : cellPPr.addNewSpacing();
if (tmpSpacing.getAfter() != null) {
cellSpacing.setAfter(tmpSpacing.getAfter());
}
if (tmpSpacing.getAfterAutospacing() != null) {
cellSpacing.setAfterAutospacing(tmpSpacing
.getAfterAutospacing());
}
if (tmpSpacing.getAfterLines() != null) {
cellSpacing.setAfterLines(tmpSpacing.getAfterLines());
}
if (tmpSpacing.getBefore() != null) {
cellSpacing.setBefore(tmpSpacing.getBefore());
}
if (tmpSpacing.getBeforeAutospacing() != null) {
cellSpacing.setBeforeAutospacing(tmpSpacing
.getBeforeAutospacing());
}
if (tmpSpacing.getBeforeLines() != null) {
cellSpacing.setBeforeLines(tmpSpacing.getBeforeLines());
}
if (tmpSpacing.getLine() != null) {
cellSpacing.setLine(tmpSpacing.getLine());
}
if (tmpSpacing.getLineRule() != null) {
cellSpacing.setLineRule(tmpSpacing.getLineRule());
}
}
// 复制段落缩进信息
CTInd tmpInd = tmpPPr.getInd();
if (tmpInd != null) {
CTInd cellInd = cellPPr.getInd() != null ?

cellPPr.getInd()
: cellPPr.addNewInd();
if (tmpInd.getFirstLine() != null) {
cellInd.setFirstLine(tmpInd.getFirstLine());
}
if (tmpInd.getFirstLineChars() != null) {
cellInd.setFirstLineChars(tmpInd.getFirstLineChars());
}
if (tmpInd.getHanging() != null) {
cellInd.setHanging(tmpInd.getHanging());
}
if (tmpInd.getHangingChars() != null) {
cellInd.setHangingChars(tmpInd.getHangingChars());
}
if (tmpInd.getLeft() != null) {
cellInd.setLeft(tmpInd.getLeft());
}
if (tmpInd.getLeftChars() != null) {
cellInd.setLeftChars(tmpInd.getLeftChars());
}
if (tmpInd.getRight() != null) {
cellInd.setRight(tmpInd.getRight());
}
if (tmpInd.getRightChars() != null) {
cellInd.setRightChars(tmpInd.getRightChars());
}
}
}
}
}


/**
* 正则匹配字符串

* @param str
* @return
*/
private Matcher matcher(String str) {
Pattern pattern = Pattern.compile("\\$\\{(.+?)\\}",
Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(str);
return matcher;
}


/**
* 正则匹配字符串

* @param str
* @return
*/
private Matcher matcherRow(String str) {
Pattern pattern = Pattern.compile("\\$\\[(.+?

)\\]",
Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(str);
return matcher;
}


/**
* 关闭输入流

* @param is
*/
private void close(InputStream is) {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}


/**
* 关闭输出流

* @param os
*/
private void close(OutputStream os) {
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

}


这篇关于POI动态生成word2007加强版的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/387539

相关文章

Java使用Javassist动态生成HelloWorld类

《Java使用Javassist动态生成HelloWorld类》Javassist是一个非常强大的字节码操作和定义库,它允许开发者在运行时创建新的类或者修改现有的类,本文将简单介绍如何使用Javass... 目录1. Javassist简介2. 环境准备3. 动态生成HelloWorld类3.1 创建CtC

Python从Word文档中提取图片并生成PPT的操作代码

《Python从Word文档中提取图片并生成PPT的操作代码》在日常办公场景中,我们经常需要从Word文档中提取图片,并将这些图片整理到PowerPoint幻灯片中,手动完成这一任务既耗时又容易出错,... 目录引言背景与需求解决方案概述代码解析代码核心逻辑说明总结引言在日常办公场景中,我们经常需要从 W

C#使用Spire.XLS快速生成多表格Excel文件

《C#使用Spire.XLS快速生成多表格Excel文件》在日常开发中,我们经常需要将业务数据导出为结构清晰的Excel文件,本文将手把手教你使用Spire.XLS这个强大的.NET组件,只需几行C#... 目录一、Spire.XLS核心优势清单1.1 性能碾压:从3秒到0.5秒的质变1.2 批量操作的优雅

Python使用python-pptx自动化操作和生成PPT

《Python使用python-pptx自动化操作和生成PPT》这篇文章主要为大家详细介绍了如何使用python-pptx库实现PPT自动化,并提供实用的代码示例和应用场景,感兴趣的小伙伴可以跟随小编... 目录使用python-pptx操作PPT文档安装python-pptx基础概念创建新的PPT文档查看

在ASP.NET项目中如何使用C#生成二维码

《在ASP.NET项目中如何使用C#生成二维码》二维码(QRCode)已广泛应用于网址分享,支付链接等场景,本文将以ASP.NET为示例,演示如何实现输入文本/URL,生成二维码,在线显示与下载的完整... 目录创建前端页面(Index.cshtml)后端二维码生成逻辑(Index.cshtml.cs)总结

Python实现数据可视化图表生成(适合新手入门)

《Python实现数据可视化图表生成(适合新手入门)》在数据科学和数据分析的新时代,高效、直观的数据可视化工具显得尤为重要,下面:本文主要介绍Python实现数据可视化图表生成的相关资料,文中通过... 目录前言为什么需要数据可视化准备工作基本图表绘制折线图柱状图散点图使用Seaborn创建高级图表箱线图热

SQLServer中生成雪花ID(Snowflake ID)的实现方法

《SQLServer中生成雪花ID(SnowflakeID)的实现方法》:本文主要介绍在SQLServer中生成雪花ID(SnowflakeID)的实现方法,文中通过示例代码介绍的非常详细,... 目录前言认识雪花ID雪花ID的核心特点雪花ID的结构(64位)雪花ID的优势雪花ID的局限性雪花ID的应用场景

Django HTTPResponse响应体中返回openpyxl生成的文件过程

《DjangoHTTPResponse响应体中返回openpyxl生成的文件过程》Django返回文件流时需通过Content-Disposition头指定编码后的文件名,使用openpyxl的sa... 目录Django返回文件流时使用指定文件名Django HTTPResponse响应体中返回openp

go动态限制并发数量的实现示例

《go动态限制并发数量的实现示例》本文主要介绍了Go并发控制方法,通过带缓冲通道和第三方库实现并发数量限制,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面... 目录带有缓冲大小的通道使用第三方库其他控制并发的方法因为go从语言层面支持并发,所以面试百分百会问到

python生成随机唯一id的几种实现方法

《python生成随机唯一id的几种实现方法》在Python中生成随机唯一ID有多种方法,根据不同的需求场景可以选择最适合的方案,文中通过示例代码介绍的非常详细,需要的朋友们下面随着小编来一起学习学习... 目录方法 1:使用 UUID 模块(推荐)方法 2:使用 Secrets 模块(安全敏感场景)方法