这段时间在研究POI设置Excel样式。
在对页面打印设置的时候,遇到一个问题,这里记录一下,和大家分享一下我的解决方案。
问题描述:在用POI设置页边距的时候,POI抛出异常:IllegalArgumentException: Unknown margin constant: 4
经过我的研究发现,这是POI内部的一个BUG。
设置页边距代码:
sheet.setMargin(HSSFSheet.BottomMargin, 0.5); //下页边距 sheet.setMargin(HSSFSheet.LeftMargin, 0.25); //左页边距 sheet.setMargin(HSSFSheet.RightMargin, 0.25); //右页边距 sheet.setMargin(HSSFSheet.TopMargin, 0.5); //上页边距 sheet.setMargin(HSSFSheet.HeaderMargin, 0.25); //头页边距 sheet.setMargin(HSSFSheet.FooterMargin, 0.25); //脚页边距
在org.apache.poi.ss.usermodel.Sheet接口里定义了如下6个常量值
public static final short LeftMargin = 0; public static final short RightMargin = 1; public static final short TopMargin = 2; public static final short BottomMargin = 3; public static final short HeaderMargin = 4; public static final short FooterMargin = 5;
但一直跟下去,在org.apache.poi.hssf.record.aggregates.PageSettingsBlock里有这样一个方法:
public void setMargin(short margin, double size) { Margin m = getMarginRec(margin); if (m == null) { switch (margin) { case InternalSheet.LeftMargin: _leftMargin = new LeftMarginRecord(); m = _leftMargin; break; case InternalSheet.RightMargin: _rightMargin = new RightMarginRecord(); m = _rightMargin; break; case InternalSheet.TopMargin: _topMargin = new TopMarginRecord(); m = _topMargin; break; case InternalSheet.BottomMargin: _bottomMargin = new BottomMarginRecord(); m = _bottomMargin; break; default : throw new IllegalArgumentException( "Unknown margin constant: " + margin ); } } m.setMargin( size ); }
这里只判断了前四种页边距,没有判断设置HeaderMargin 和FooterMargin 两种类型,所以编译期间没有错误。但在运行期间就抛出了IllegalArgumentException: Unknown margin constant: 4;异常
POI3.6, POI3.7, POI3.8beta3三个版本存在一样的问题。
我的解决方案:换一种设置方法即可(主要针对于头和脚)
hssfSheet.getPrintSetup().setFooterMargin(0.05);
hssfSheet.getPrintSetup().setHeaderMargin(0.05);
这样就可以很轻松的解决问题了。
Thanks
Jack.Li
Email Address: jackxlee89@yahoo.cn
qq:523072842
2012.08.17
There are two ways of constructing a software design: One way is to make it so simple that there are obviously no deficiencies, and the other way is to make it so complicated that there are no obvious deficiencies. The first method is far more difficult.