>>可点击此处下载最新版测试。
为 Java 安装 Spire.Doc
首先,您需要在 Java 程序中添加 Spire.Doc.jar 文件作为依赖项。
合并单元格时删除重复值
以下是删除 Word 表格中合并单元格中重复值的步骤。
- 创建Document类的对象并使用Document.loadFromFile()方法加载示例文档。
- 使用Document.getSections()方法获取节集合,然后使用SectionCollection.get()方法获取特定节。
- 使用Section.getTables()方法获取表集合,然后使用TableCollection.get()方法获取想要的表
- 调用mergeCell(Table table, boolean isHorizontalMerge, int index, int start, int end)方法来垂直或水平合并表格单元格。此方法会判断要合并的单元格是否具有相同的值,并且将在合并单元格中仅保留一个值。
- 使用Document.saveToFile()方法将文档保存到文件。
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(); }}

整合所有格式API处理套包Spire.office for Java正在 火热销售中!联系客服立马1分钟了解全部咨询!
标签:
声明:本站部分文章及图片源自用户投稿,如本站任何资料有侵权请您尽早请联系jinwei@zod.com.cn进行处理,非常感谢!