本篇文章将介绍通过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);
            }
        }
    }
}页眉表格添加效果:

 



 
					



