[简单]poi word2007表格按模版样式填充行数据
主要实现了按照模版行的样式填充数据,针对的是动态数据,静态数据可以直接替换变量实现,先说下缺点:1)暂未实现特殊样式填充(如列合并(跨行合并)),只能用于普通样式(如段落间距 缩进 字体 对齐)2)数据行插到模版行下面,没有实现指定位置插入
直接上代码:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List; 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.CTFonts;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTInd;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTPPr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRPr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSpacing;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTc;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTcPr; public class POI_表格_按模版样式填充数据_S3_Test {
public static void main(String[] args) throws Exception {
POI_表格_按模版样式填充数据_S3_Test t = new POI_表格_按模版样式填充数据_S3_Test();
t.insertDataToTable("f:/saveFile/temp/sys_s3_template.docx", 3, false);
} public void insertDataToTable(String filePath, int tableSize,
boolean isDelTmpRow) throws Exception {
InputStream is = new FileInputStream(filePath);
XWPFDocument doc = new XWPFDocument(is);
List<List<String>> resultList = generateTestData(4);
insertValueToTable(doc, resultList, tableSize, isDelTmpRow);
saveDocument(doc, "f:/saveFile/temp/sys_" + System.currentTimeMillis()
+ ".docx");
} /**
* @Description: 按模版行样式填充数据,暂未实现特殊样式填充(如列合并),只能用于普通样式(如段落间距 缩进 字体 对齐)
* @param resultList 填充数据
* @param tableRowSize 模版表格行数 取第一个行数相等列数相等的表格填充
* @param isDelTmpRow 是否删除模版行
*/
// TODO 数据行插到模版行下面,没有实现指定位置插入
public void insertValueToTable(XWPFDocument doc,
List<List<String>> resultList, int tableRowSize, boolean isDelTmpRow)
throws Exception {
Iterator<XWPFTable> iterator = doc.getTablesIterator();
XWPFTable table = null;
List<XWPFTableRow> rows = null;
List<XWPFTableCell> cells = null;
List<XWPFTableCell> tmpCells = null;// 模版列
XWPFTableRow tmpRow = null;// 匹配用
XWPFTableCell tmpCell = null;// 匹配用
boolean flag = false;// 是否找到表格
while (iterator.hasNext()) {
table = iterator.next();
rows = table.getRows();
if (rows.size() == tableRowSize) {
tmpRow = rows.get(tableRowSize - 1);
cells = tmpRow.getTableCells();
if (cells.size() == resultList.get(0).size()) {
flag = true;
break;
}
}
}
if (!flag) {
return;
}
tmpCells = tmpRow.getTableCells();
for (int i = 0, len = resultList.size(); i < len; i++) {
XWPFTableRow row = table.createRow();
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));
}
}
// 删除模版行
if (isDelTmpRow) {
table.removeRow(tableRowSize - 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());
}
}
}
}
} public void saveDocument(XWPFDocument document, String savePath)
throws Exception {
FileOutputStream fos = new FileOutputStream(savePath);
document.write(fos);
fos.close();
} // 生成测试数据
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);
resultList.add(list);
}
return resultList;
}
}
结果如下:
普通表格不删除模版列:

普通表格删除模版列:

带样式表格不删除模版列:

带样式表格删除模版列:

带合并单元格表格不删除模版列:

带合并单元格表格删除模版列:

原链接:http://53873039oycg.iteye.com/blog/2152759
[简单]poi word2007表格按模版样式填充行数据的更多相关文章
- 在csv表格中修改/追加某行数据
思路: 文本文件不能随意穿插信息,但是通过使用Seek()方法,可以在读取文本文件中移动光标从而修改所要修改的行. 思路步骤: 1.读取文件,打开csv文件,获取文件流,seek移动光标到开始, fo ...
- 利用Apache POI 实现简单的Excel表格导出
1.利用POI API实现简单的Excel表格导出 首先假设一个学生实体类: package com.sun.poi.domain; import java.io.Serializable; impo ...
- 简单poi操作word@2020
个人采用POI(3.16版本)一.段落部分XWPFParagraph paragraph = docxDocument.createParagraph();1.段落对齐方式paragraph.setA ...
- 创建简单的响应式HTML5模版
创建简单的响应式HTML5模版 HTML5目前发展势头良好,已经逐渐得到大部分浏览器不同程度的支持.许多web开发者也已经学习到了不少关于HTML 5的基础知识并开始试图使用HTML 5制作网页.与此 ...
- 自己实现的数据表格控件(dataTable),支持自定义样式和标题数据、ajax等各种自定义设置以及分页自定义
一.前言 也没什么好说的嘛,用了蛮多github上开源的能够实现dataTable功能的表格插件,不过都默认绑定样式啊,数据格式也设定的比较死,所以忍不住自己实现了一个简单的可自定义样式和自定义数据返 ...
- v-model指令实现简单的问卷表格
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&q ...
- css3-6 表格如何设置样式和定位样式是什么
css3-6 表格如何设置样式和定位样式是什么 一.总结 一句话总结:css可以解决所有属性设置的样式. 1.表格如何设置样式? css样式可以解决一切问题,没必要在表格上面加属性来设置样式. 7 t ...
- 11种常用css样式之表格和定位样式学习
table表格中border-collapse: collapse;/*表格边框是否合并*/border-spacing: 10px;/*表格边框之间的距离*/定位详情可以阅读position属性值4 ...
- Code First开发系列之管理数据库创建,填充种子数据以及LINQ操作详解
返回<8天掌握EF的Code First开发>总目录 本篇目录 管理数据库创建 管理数据库连接 管理数据库初始化 填充种子数据 LINQ to Entities详解 什么是LINQ to ...
随机推荐
- 在Sharepoint 2010中启用Session功能的说明文档
在Sharepoint 2010中启用Session功能的说明文档 开发环境:Windows 7系统,SharePoint Server 2010,Visual Studio 2010 按以下步骤进行 ...
- 【转】tomcat下部署 solr 5.3.1
本文转自:http://blog.csdn.net/lianghyan/article/details/49467207 solr下载: http://lucene.apache.org/solr/d ...
- Win7下虚拟机个人使用小结:Virtual PC,VMware和VirtualBox
想来用了很多年的虚拟机了,换了Win7之后,种种原因又需要使用虚拟机,这里就简单介绍和比较一下. 点击小图看大图. Virtual PC: 如果想做Windows虚拟机的话,Virtual PC在之前 ...
- MPlayer-ww 增加边看边剪切功能
解压到 D:\MPlayer-ww 运行 copy_font.bat 安装字体 LED_font.ttf 双击 MPlayer_ww_openWith.reg 添加右键播放功能 outformat.i ...
- codeforces A. Difference Row 解题报告
题目链接:http://codeforces.com/problemset/problem/347/A 题目意思:给出一个序列 a1, a2, ..., an , 通过重排序列,假设变成 x1, x2 ...
- PO/VO/BO等对象模型
PO :persistent object持久对象 1 .有时也被称为Data对象,对应数据库中的entity,可以简单认为一个PO对应数据库中的一条记录. 2 .在hibernate持久化框架中与i ...
- Human Gene Functions(poj 1080)
题目大意是:给定两组DNA序列,要你求出它们的最大相似度 每个字母与其他字母或自身和空格对应都有一个打分,求在这两个字符串中插入空格,让这两个字符串的匹配分数最大 /* 思路是很好想的,设f[i][j ...
- svn 文件夹 无法提交
[root@v01 www]# svn add localsvn/kkk/ svn: warning: 'localsvn/kkk' is already under version control ...
- oracle 10g 学习之函数和存储过程(12)
一.函数 1. 函数的 helloworld: 返回一个 "helloworld--!" 的字符串 create or replace function helloworld re ...
- [杂] ASP.NET MVC 之 Route To MvcHandler
首先,本文参考了不少东东,仅供Q_L_H自己使用,ZZ自己负责.先上一张全家福: HttpModules and HttpHandlers ASP.NET MVC 是 HttpHandler. Url ...