参考文章:http://www.xuebuyuan.com/791774.html (感谢)
问题描述:
在修改别人的代码时遇到用jxl 读取生成的excel模板,在读取过程中一切正常,但在写入新的EXCEL时调用.write()方法出现下标越界异常,跟着读取数据未发现问题,抛出异常显示未jxl引用包中相关,查询资料,发现这篇文章作者描述的情况及出现的问题与本人相似90%;Excel模板版本是office2007,具体模板的生成制作时的版本不清楚,模板中内容格式设置也不清楚的情况下,我的异常显示FormattingRecords.class这个类 rationalize方法中,根据参考文章中作者描述的方法,在相关代码处捕获异常,跳出循环后,代码执行正常。遇到类似问题的同学,可尝试参考修改,将jxl包中出现异常位置反编译跟踪修改。
部分代码:(红色为修改代码)
public IndexMapping rationalize(IndexMapping fontMapping, IndexMapping formatMapping)
{
XFRecord xfr = null;
for (Iterator it = this.xfRecords.iterator(); it.hasNext(); )
{
xfr = (XFRecord)it.next();
if (xfr.getFormatRecord() >= 164)
{
xfr.setFormatIndex(formatMapping.getNewIndex(xfr.getFormatRecord()));
}
xfr.setFontIndex(fontMapping.getNewIndex(xfr.getFontIndex()));
}
ArrayList newrecords = new ArrayList(21);
IndexMapping mapping = new IndexMapping(this.xfRecords.size());
int numremoved = 0;
int numXFRecords = Math.min(21, this.xfRecords.size());
for (int i = 0; i < numXFRecords; i++)
{
newrecords.add(this.xfRecords.get(i));
mapping.setMapping(i, i);
}
if (numXFRecords < 21)
{
logger.warn("There are less than the expected minimum number of XF records");
return mapping;
}
for (int i = 21; i < this.xfRecords.size(); i++)
{
XFRecord xf = (XFRecord)this.xfRecords.get(i);
boolean duplicate = false;
Iterator it = newrecords.iterator();
while ((it.hasNext()) && (!
duplicate))
{
XFRecord xf2 = (XFRecord)it.next();
if (xf2.equals(xf))
{
duplicate = true;
mapping.setMapping(i, mapping.getNewIndex(xf2.getXFIndex()));
numremoved++;
}
}
if (!duplicate)
{
newrecords.add(xf);
mapping.setMapping(i, i - numremoved);
}
}
for (Iterator i = this.xfRecords.iterator(); i.hasNext(); ) {
try
{
XFRecord xf = (XFRecord)i.next();
xf.rationalize(mapping);
} catch (Exception e) {
break;
}
}
this.xfRecords = newrecords;
return mapping;
}