POI操作Word中的表格XWPFTable,在指定位置插入行


最近由於客戶使用Word文檔展示表格中的數據,我TM。。。Excel它不香嘛,為什么要用Word去展示表格呢???

但是呢、客戶就是上帝,上帝讓我們干嘛我們就要干嘛。

1:有這樣一個需求,在已有的Word模版中的表格動態的插入行

不解釋了,直接復制下方代碼拿去用

String path=“word文件路徑”;
FileInputStream in = new FileInputStream(path);
XWPFDocument hwpf = new XWPFDocument(in);
List<XWPFTable> tables = 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());
		//或許需要復制的行的列
		List<XWPFTableCell> copyCells = 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());
				} 
			} 
		}
		
	}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM