原創|使用教程|編輯:張瑩心|2021-11-01 11:01:43.203|閱讀 743 次
概述:Spire.Doc 提供Table.applyVerticalMerge()方法垂直合并表格單元格和 Table.applyHorizo??ntalMerge() 方法水平合并表格單元格。默認情況下,如果要合并的單元格包含相同的值,則合并的單元格將具有重復的值。本文將演示如何使用Spire.Doc for Java的自定義方法刪除合并單元格中的重復值。
# 界面/圖表報表/文檔/IDE等千款熱門軟控件火熱銷售中 >>
Spire.Doc for Java 是一款專業的Java Word組件,開發人員使用它可以輕松地將Word文檔創建、讀取、編輯、轉換和打印等功能集成到自己的Java應用程序中。
Spire.Doc 提供Table.applyVerticalMerge()方法垂直合并表格單元格和 Table.applyHorizontalMerge() 方法水平合并表格單元格。默認情況下,如果要合并的單元格包含相同的值,則合并的單元格將具有重復的值。本文將演示如何使用Spire.Doc for Java的自定義方法刪除合并單元格中的重復值。
>>可點擊此處下載最新版測試。
import com.spire.doc.*; import com.spire.doc.interfaces.ITable; public class MergeCells { public static void main(String[] args) throws Exception { //Create an object of Document class and load the sample document. Document document = new Document(); document.loadFromFile("Sample.docx"); //Get the first section Section section = document.getSections().get(0); //Get the first table Table table = section.getTables().get(0); //Invoike mergeCell()method to merge cells vertically mergeCell(table, false, 0, 1, 3); //Invoike mergeCell()method to merge cell horizontally mergeCell(table, true, 0, 4, 5); //Save the document to file document.saveToFile("MergeTable.docx",FileFormat.Docx_2013); } //Customize a mergeCell() method to remove the duplicate values while merging cells public static void mergeCell(Table table, boolean isHorizontalMerge, int index, int start, int end) { if (isHorizontalMerge) { //Get a cell from table TableCell firstCell = table.get(index, start); //Invoke getCellText() method to get the cell’s text String firstCellText = getCellText(firstCell); for (int i = start + 1; i <= end; i++) { TableCell cell1 = table.get(index, i); //Check if the text is the same as the first cell if (firstCellText.equals(getCellText(cell1))) { //If yes, clear all the paragraphs in the cell cell1.getParagraphs().clear(); } } //Merge cells horizontally table.applyHorizontalMerge(index, start, end); } else { TableCell firstCell = table.get(start, index); String firstCellText = getCellText(firstCell); for (int i = start + 1; i <= end; i++) { TableCell cell1 = table.get(i, index); if (firstCellText.equals(getCellText(cell1))) { cell1.getParagraphs().clear(); } } //Merge cells vertically table.applyVerticalMerge(index, start, end); } } public static String getCellText(TableCell cell) { StringBuilder text = new StringBuilder(); //Traverse all the paragraphs of a cell for (int i = 0; i < cell.getParagraphs().getCount(); i++) { //Get every paragraph’s text and append it to StringBuilder text.append(cell.getParagraphs().get(i).getText().trim()); } return text.toString(); } }
本站文章除注明轉載外,均為本站原創或翻譯。歡迎任何形式的轉載,但請務必注明出處、不得修改原文相關鏈接,如果存在內容上的異議請郵件反饋至chenjj@fc6vip.cn