本文介绍在 Java程序中如何删除Word表格(即将整个Table表格删除)和删除Word表格内容(即删除表格中的数据内容,这里也可以根据需要实现删除表格样式,表格单元格中的段落等)的方法。
使用工具:Free Spire.Doc for Java(免费版),可通过官网
下载Jar包,并解压将lib文件夹下的jar文件导入Java程序;也可以通过
Maven仓库下载导入。如下导入效果:
1.
删除表格
import com.spire.doc.*;
import com.spire.doc.interfaces.ITable;
public class RemoveTable {
public static void main(String[] args) {
//创建实例
Document doc = new Document();
//加载Word文档
doc.loadFromFile("test.docx");
//获取Section
Section section = doc.getSections().get(0);
//获取表格
ITable table = section.getTables().get(0);
//删除表格
section.getTables().remove(table);
//保存文档
doc.saveToFile("RemoveTable.docx",FileFormat.Docx_2013);
doc.dispose();
}
}
表格删除前后效果:
2.
删除表格内容
import com.spire.doc.*;
public class RemoveTableContent {
public static void main(String[] args) {
//创建实例,加载测试文档
Document doc = new Document();
doc.loadFromFile("test.docx");
//获取Section
Section section = doc.getSections().get(0);
//获取表格
Table table =section.getTables().get(0);
//遍历表格每行
for (int i = 0; i
//获取表格行
TableRow row = table.getRows().get(i);
//遍历每行中的每个单元格
for(int j = 0; j
{
//获取单元格
TableCell cell = row.getCells().get(j);
cell.getChildObjects().clear();//清除所有子对象
//cell.getCellFormat().clearFormatting();//清除单元格格式
//cell.getParagraphs().removeAt(0);//删除单元格中的段落
}
}
//保存文档
doc.saveToFile("RemoveContent.docx",FileFormat.Docx_2013);
doc.dispose();
}
}
表格内容删除前后效果:
(完)