嵌套表格,即在一个大的表格单元格中再嵌进去一个或几个小的表格,使表格内容布局合理。以下示例中,将介绍通过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);
}
}
嵌套表格添加效果: