wxpython 表格 当前位置增加一行_POI操作Word中的表格XWPFTable,在指定位置插入行...

最近由于客户使用Word文档展示表格中的数据,我TM。。。Excel它不香嘛,为什么要用Word去展示表格呢???

但是呢、客户就是上帝,上帝让我们干嘛我们就要干嘛。

1:有这样一个需求,在已有的Word模版中的表格动态的插入行

不解释了,直接复制下方代码拿去用

String path=“word文件路径”;

FileInputStream in = new FileInputStream(path);

XWPFDocument hwpf = new XWPFDocument(in);

Listtables = hwpf.getTables();//获取word中所有的表格

FileOutputStream out = new FileOutputStream(path);

XWPFTable table = tables.get(0);//获取第一个表格

insertRow(table, 3, 5);//此方法在下方,直接复制拿走

hwpf.write(out);

out.flush();

out.close();

2:主要代码在这里

在word文档中的表格指定位置插入一行,并复制某一行的样式到新增行

/**

* insertRow 在word表格中指定位置插入一行,并将某一行的样式复制到新增行

* @param copyrowIndex 需要复制的行位置

* @param newrowIndex 需要新增一行的位置

* */

public static void insertRow(XWPFTable table, int copyrowIndex, int newrowIndex) {

// 在表格中指定的位置新增一行

XWPFTableRow targetRow = table.insertNewTableRow(newrowIndex);

// 获取需要复制行对象

XWPFTableRow copyRow = table.getRow(copyrowIndex);

//复制行对象

targetRow.getCtRow().setTrPr(copyRow.getCtRow().getTrPr());

//或许需要复制的行的列

ListcopyCells = copyRow.getTableCells();

//复制列对象

XWPFTableCell targetCell = null;

for (int i = 0; i < copyCells.size(); i++) {

XWPFTableCell copyCell = copyCells.get(i);

targetCell = targetRow.addNewTableCell();

targetCell.getCTTc().setTcPr(copyCell.getCTTc().getTcPr());

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

targetCell.getParagraphs().get(0).getCTP().setPPr(copyCell.getParagraphs().get(0).getCTP().getPPr());

if (copyCell.getParagraphs().get(0).getRuns() != null

&& copyCell.getParagraphs().get(0).getRuns().size() > 0) {

XWPFRun cellR = targetCell.getParagraphs().get(0).createRun();

cellR.setBold(copyCell.getParagraphs().get(0).getRuns().get(0).isBold());

}

}

}

}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值