文本介绍如何使用Spire.Presentation for Java在现有的PPT表格中添加或删除行和列。
测试文档:
添加行和列
import com.spire.presentation.*;
public class AddRowAndColumn {
public static void main(String[] args) throws Exception {
//加载示例文档
Presentation presentation = new Presentation();
presentation.loadFromFile("C:\\Users\\Administrator\\Desktop\\input.pptx");
//获取表格
ITable table = null;
for (Object shape : presentation.getSlides().get(0).getShapes()) {
if (shape instanceof ITable) {
table = (ITable) shape;
//将最后一行作为新行添加到表格下方
int rowCount = table.getTableRows().getCount();
TableRow row = table.getTableRows().get(rowCount - 1);
table.getTableRows().append(row);
//获取新行,并设置每个单元格的文本
rowCount = table.getTableRows().getCount();
row = table.getTableRows().get(rowCount - 1);
row.get(0).getTextFrame().setText("美国");
row.get(1).getTextFrame().setText("华盛顿");
row.get(2).getTextFrame().setText("北美洲");
row.get(3).getTextFrame().setText("9372610");
//将最后一列作为新列添加到表格右方
int colCount = table.getColumnsList().getCount();
TableColumn column =table.getColumnsList().get(colCount-1);
table.getColumnsList().add(column);
//获取新列,并设置每个单元格的文本
colCount = table.getColumnsList().getCount();
column = table.getColumnsList().get(colCount-1);
column.get(0).getTextFrame().setText("人口");
column.get(1).getTextFrame().setText("32370000");
column.get(2).getTextFrame().setText("7350000");
column.get(3).getTextFrame().setText("15040000");
column.get(4).getTextFrame().setText("26500000");
column.get(5).getTextFrame().setText("329740000");
}
}
//保存文档
presentation.saveToFile("output/AddRowAndColumn.pptx", FileFormat.PPTX_2013);
}
}
删除行和列
import com.spire.presentation.FileFormat;
import com.spire.presentation.ITable;
import com.spire.presentation.Presentation;
public class DeleteRowAndColumn {
public static void main(String[] args) throws Exception {
//加载示例文档
Presentation presentation = new Presentation();
presentation.loadFromFile("C:\\Users\\Administrator\\Desktop\\input.pptx");
//获取表格
ITable table = null;
for (Object shape : presentation.getSlides().get(0).getShapes()) {
if (shape instanceof ITable) {
table = (ITable) shape;
//删除第二列
table.getColumnsList().removeAt(1, false);
//删除第二行
table.getTableRows().removeAt(1, false);
}
}
//保存文档
presentation.saveToFile("output/DeleteRowAndColumn.pptx", FileFormat.PPTX_2013);
}
}