本文将介绍使用 Spire.Doc for Java 来添加行或者列的方法。
添加表格行
import com.spire.doc.*;
public class AddRow {
public static void main(String[] args){
//加载测试文档
Document doc = new Document();
doc.loadFromFile("sample.docx");
//获取表格
Section section = doc.getSections().get(0);
Table table = section.getTables().get(0);
table.addRow();//默认在表格最下方插入一行
//table.getRows().insert(2,table.addRow());//在表格中第3行插入一行
//table.addRow(4);//默认在表格最下方添加4个单元格
//table.addRow(true,2);//带格式在最后一行添加2个单元格
//table.addRow(false,2);//不带格式在最后一行添加2个单元格
//保存文档
doc.saveToFile("addrow.docx",FileFormat.Docx_2013);
doc.dispose();
}
}
表格行添加效果:
添加表格列
import com.spire.doc.*;
import com.spire.doc.documents.BorderStyle;
import java.awt.*;
public class AddColumn {
public static void main(String[] args){
//加载测试文档
Document doc = new Document();
doc.loadFromFile("sample.docx");
//获取表格
Section section = doc.getSections().get(0);
Table table = section.getTables().get(0);
//获取表格单元格宽度及类型
float width = table.get(0,0).getWidth();
CellWidthType type = table.get(0,0).getCellWidthType();
//遍历表格每一行
for (int i = 0; i < table.getRows().getCount(); i++) {
TableRow row = table.getRows().get(i);//获取表格每一行
Color color = row.getCells().get(0).getCellFormat().getBackColor();//获取表格单元格背景色
//基于表格每行,在最后添加一个单元格,并设置单元格格式
TableCell cell = row.addCell(true);//默认在最后一列添加单元格
cell.setWidth(width);
cell.setCellWidthType(type);
cell.getCellFormat().getBorders().setBorderType(BorderStyle.Single);
cell.getCellFormat().setBackColor(color);
//如需在指定位置插入列,基于以上代码并增加下面一行代码即可
//row.getCells().insert(2,cell);//插入一列作为第三列
}
//保存文档
doc.saveToFile("addcolumn.docx", FileFormat.Docx_2013);
doc.dispose();
}
}
表格列添加效果: