首页 > 技术文章 > Apache POI - 记导出Excel所遇到的坑

yijtz 2017-01-22 10:04 原文

Apache POI是个用Java编写的免费开源的,用来操作Microsoft Office格式的文档。实际工作中,经常需要把数据导入到Excel表中。这个目前来说,应该是比较好用的。以前用过NPOI,是其的.Net版本实现,原理差不太多。这篇文章主要说我遇到的问题,并记录一下,好了,上代码:

public class HelloWorld{
  private String name;

  private int age;    

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

}

上面是一个简单的JavaBean,我在写入Excel操作时使用了泛型,相应字段直接可以写入到Excel相应的列中,非常方便。泛型关键段方法如下:

public void exportExcelHasCellStyle(int startIndex,HSSFSheet sheet,Collection<T> dataset,HSSFCellStyle style)
    {
        HSSFRow row = null;
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);//居中显示
        // 遍历集合数据,产生数据行
        Iterator<T> it = dataset.iterator();
        int index = startIndex;
        while (it.hasNext()) {
            index++;
            row = sheet.getRow(index);
            T t = (T) it.next();
            // 利用反射,根据javabean属性的先后顺序,动态调用getXxx()方法得到属性值
            Field[] fields = t.getClass().getDeclaredFields();
            for (int i = 0; i < fields.length; i++) {
                HSSFCell cell = row.createCell(i);
                cell.setCellStyle(style);
                Field field = fields[i];
                String fieldName = field.getName();
                String getMethodName = "get"
                        + fieldName.substring(0, 1).toUpperCase()
                        + fieldName.substring(1);
                try {
                    Class tCls = t.getClass();
                    Method getMethod = tCls.getMethod(getMethodName,
                            new Class[] {});
                    Object value = getMethod.invoke(t, new Object[] {});
                    // 判断值的类型后进行强制类型转换
                    String textValue = null;
                    if(value != null)
                    {
                        textValue = value.toString();
                    }
                    cell.setCellValue(textValue);
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
    }

其实,上面的代码并没有什么问题,用户代码传入的相关的JavaBean数据集合(dataset)以及样式(style),就可以从表(sheet)的某一行(startIndex)开始写入数据了,如果数据的行数少于Excel已经打开的行数,执行到这一句代码 HSSFCell cell = row.createCell(i);时并没报NPE,经过多次调试才发现,超过了模板Excel打开的行数时,如果还使用sheet.getRow(index)将返回null,导致这个NPE时报进不报的,耐心的调试了一会儿,在row.createCell(i);加了个判断,如果为null,则调用createRow(index)再去创建一行,发现所有的超过模板Excel打开的行数时也能正常的导出了。

推荐阅读