本篇文章将介绍通过spire.doc for java添加表格到word页眉的方法。
import com.spire.doc.*;
import com.spire.doc.documents.defaulttablestyle;
import com.spire.doc.documents.horizontalalignment;
import com.spire.doc.documents.tablerowheighttype;
import com.spire.doc.documents.verticalalignment;
import com.spire.doc.fields.textrange;
public class addtabletoheader {
public static void main(string[]args){
//加载需要添加页眉页脚的文档
document doc= new document("test.docx");
section sec = doc.getsections().get(0);
//调用方法添加页眉页脚
addheaderfooter(sec);
//保存文档
doc.savetofile("addtabletoheader.docx");
}
private static void addheaderfooter(section sec){
//添加表格到页眉
headerfooter header = sec.getheadersfooters().getheader();
table table = header.addtable();
table.resetcells(2,2);//指定表格行数、列数
table.applystyle(defaulttablestyle.light_grid);//设置表格样式
//声明数组内容
string[][] data ={
new string[]{"出版号","日期"},
new string[]{"sc12546","2019年7月24日"},
};
//填充数组内容到表格
for (int i = 0; i < data.length; i ) {
tablerow datarow = table.getrows().get(i);
datarow.setheight(20f);
datarow.setheighttype(tablerowheighttype.exactly);
for (int j = 0; j < data[i].length; j ) {
datarow.getcells().get(j).setwidth(120f);
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(12f);
range.getownerparagraph().getformat().sethorizontalalignment(horizontalalignment.center);
}
}
}
}
页眉表格添加效果: