JAVA整合Flex导出数据库中的数据 (续集2)

     之前写的二篇关于数据导出的文章,都没有经过仔细测试,比如插入上百条数据时,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的情况下,下载才正常)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值