嵌套表格,即在一个大的表格单元格中再嵌进去一个或几个小的表格,使表格内容布局合理。以下示例中,将介绍通过spire.doc for java 在word表格中添加嵌套表格的方法。
import com.spire.doc.*;
import com.spire.doc.documents.horizontalalignment;
import com.spire.doc.documents.rowalignment;
import com.spire.doc.documents.tablerowheighttype;
import com.spire.doc.documents.verticalalignment;
import com.spire.doc.fields.textrange;
public class nestedtable {
public static void main(string[]args){
//加载测试文档
document doc = new document("sample.docx");
section sec = doc.getsections().get(0);
//获取指定表格中的单元格,并设置行高、列宽
table table = sec.gettables().get(0);
table.getrows().get(0).setheight(130);
table.getrows().get(0).getcells().get(0).setwidth(400);
//添加嵌套表格到指定单元格
table nestedtable = table.get(0,0).addtable(true);
nestedtable.gettableformat().sethorizontalalignment(rowalignment.center);//设置嵌套表格在单元格中的对齐方式
nestedtable.resetcells(4,4);//指定嵌套表格行数、列数
nestedtable.autofit(autofitbehaviortype.auto_fit_to_contents);//设置嵌套表格内容自适应类型
//声明表格数组内容
string[][] data ={
new string[]{"编号","产品名","最新版本","发布日期",},
new string[]{"1","spire.office for java","v2.2.0","2019-06-21"},
new string[]{"2","spire.doc for java","v2.6.1","2019-06-18"},
new string[]{"3","spire.pdf for java","v2.6.2","2019-06-14"},
};
//填充数组内容到嵌套表格
for (int i = 0; i < data.length; i ) {
tablerow datarow = nestedtable.getrows().get(i);
datarow.getcells().get(i).setwidth(100);
datarow.setheight(18);
datarow.setheighttype(tablerowheighttype.exactly);
for (int j = 0; j < data[i].length; j ) {
datarow.getcells().get(j).getcellformat().setverticalalignment(verticalalignment.middle);
textrange range = datarow.getcells().get(j).addparagraph().appendtext(data[i][j]);
range.getcharacterformat().setfontname("楷体");
range.getcharacterformat().setfontsize(11f);
range.getownerparagraph().getformat().sethorizontalalignment(horizontalalignment.center);
}
}
//保存文档
doc.savetofile("nesedtable.docx",fileformat.docx_2010);
}
}
嵌套表格添加效果: