之前写的二篇关于数据导出的文章,都没有经过仔细测试,比如插入上百条数据时,Excel数据导出是否正常,今天又对这个程序试了一试,发现导入200条数据时,数据导不出来。经过笔者仔细断点,条件断点测试,问题终于得解,是在i=29时,Row,Cell对象为空时,导致空指针异常。在这里,我做判断,如果它们为空的话,则进行创建即可,并赋予相关属性。以下是经笔者重构后的代码。如下所示:
/**
* 组装数据至excel文件中
*
* @param path
* @param filename
* @param response
* @param sample_data
* @throws Exception
*/
public void assembleData(String path, String filename,
HttpServletResponse response, Object[][] sample_data)
throws Exception {
InputStream inputStream = new FileInputStream(path + filename);
// 从流中得到Workbook
Workbook wb = WorkbookFactory.create(inputStream);
// 得到第一个sheet
Sheet sheet = wb.getSheetAt(0);
// 设置数据
for (int i = 0; i < sample_data.length; i++) {
Row row = sheet.getRow(1 + i);
//如果行为null,则进行创建
if (row == null) {
row = sheet.createRow(1 + i);
}
for (int j = 0; j < sample_data[i].length; j++) {
Cell cell = row.getCell(j);
if (sample_data[i][j] == null)
continue;
//如果单元格为null值,创建这个cell,并设置其属性
if (cell == null) {
cell = row.createCell(j);
CellStyle style = wb.createCellStyle();
style.setAlignment(CellStyle.ALIGN_CENTER);
style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
cell.setCellStyle(style);
}
if (sample_data[i][j] instanceof String) {
cell.setCellValue((String) sample_data[i][j]);
} else if (sample_data[i][j] instanceof Double) {
cell.setCellValue((Double) sample_data[i][j]);
} else if (sample_data[i][j] instanceof Long) {
cell.setCellValue((Long) sample_data[i][j]);
} else if (sample_data[i][j] instanceof Integer) {
cell.setCellValue((Integer) sample_data[i][j]);
}
}
}
// Write the output to a response object
wb.write(response.getOutputStream());
}
其它代码保持不变。
(注意,在IE9的情况下,下载才正常)