本文将从以下几个方面展示如何使用spire.xls for java插入图片或文本页眉页脚以及对页眉页脚进行格式化
- 添加图片到页眉
- 添加文字到页脚
- 为奇偶页添加不同的页眉页脚
添加图片到页眉
import com.spire.xls.*;
import javax.imageio.imageio;
import java.awt.image.bufferedimage;
import java.io.*;
public class imageheader {
public static void main(string[] args) throws ioexception {
string imagefile = "logo.png";
//新建excel workbook
workbook workbook = new workbook();
//获取第一个工作表
worksheet worksheet = workbook.getworksheets().get(0);
//加载图片
bufferedimage image = imageio.read( new file(imagefile));
//设置图片页眉
worksheet.getpagesetup().setleftheaderimage(image);
worksheet.getpagesetup().setleftheader("&g");
//设置显示样式
worksheet.setviewmode(viewmode.layout);
//保存文档
workbook.savetofile("output/imageheader.xlsx", excelversion.version2010);
}
}
图片页眉效果图:
添加文字到页脚
import com.spire.xls.*;
public class textfooter {
public static void main(string[] args) {
//新建excel工作簿
workbook workbook = new workbook();
//获取第一个工作表
worksheet worksheet = workbook.getworksheets().get(0);
//设置页脚文字及位置
worksheet.getpagesetup().setcenterfooter("spire.xls for java");
//设置显示样式
worksheet.setviewmode(viewmode.layout);
//保存文档
workbook.savetofile("output/textfooter.xlsx", excelversion.version2010);
}
}
文字页脚效果图:
为奇偶页添加不同的页眉页脚
import com.spire.xls.*;
public class headerfooter {
public static void main(string[] args) {
//新建excel工作簿
workbook workbook = new workbook();
//获取第一个工作表
worksheet worksheet = workbook.getworksheets().get(0);
//设置第一页,第二页
worksheet.getcellrange("a1").settext("page 1");
worksheet.getcellrange("j1").settext("page 2");
//将setdifferentoddeven的值设为1, 表示奇数页和偶数页可以分别设置页眉页
worksheet.getpagesetup().setdifferentoddeven((byte)1);
//设置奇数页及偶数页页眉页脚,样式和颜色
worksheet.getpagesetup().setoddheaderstring( "&\"arial\"&12&b&kffc000 odd_header");
worksheet.getpagesetup().setoddfooterstring ( "&\"arial\"&12&b&kffc000 odd_footer");
worksheet.getpagesetup().setevenheaderstring ( "&\"arial\"&12&b&kff0000 even_header");
worksheet.getpagesetup().setevenfooterstring ( "&\"arial\"&12&b&kff0000 even_footer");
//设置显示样式
worksheet.setviewmode(viewmode.layout);
//保存文档
workbook.savetofile("output/different.xlsx", excelversion.version2010);
}
}