java读取数据库中的数据并存储到excel中去

我们在开发中可能会遇到将数据库中的数据都取出来存储到excel中去

在操作过程中用到了poi-3.17.jar包

/**
	 * 构建Excel
	 * map参数 用来保存数据 保存的是从Handler传递过来的数据
	 * workBook 操作Excel 需要导入poi jar包
	 * 
	 */
	@Override
	protected void buildExcelDocument(Map<String, Object> map,
			HSSFWorkbook workBook, HttpServletRequest request,
			HttpServletResponse response)
			throws Exception {
		
		//excel文件名
		String fileName = "学生excel.xls";
		//设置响应的编码格式
		response.setCharacterEncoding("UTF-8");
		//设置响应类型
		response.setContentType("application/ms-excel");
		//设置响应头
		response.setHeader("Content-Disposition",
				"inline;filename="+
				 new String(fileName.getBytes(),"iso8859-1"));
		
		//构建excel
		//map集合中 保存了所有学生的list集合,key stuList
		List<StuModel> list = (List<StuModel>)map.get("stuList");
		//创建一个sheet标签
		HSSFSheet sheet = workBook.createSheet("学生列表");
		//创建第一行(头)
		HSSFRow head = sheet.createRow(0);
		//创建列
		head.createCell(0).setCellValue("学生姓名");
		head.createCell(1).setCellValue("年龄");
		head.createCell(2).setCellValue("性别");
		head.createCell(3).setCellValue("地址");
		
		//根据具体数据集合创建其他的行和列
		for(int i=1;i<=list.size();i++){
			HSSFRow dataRow = sheet.createRow(i);
			//循环时将实体类获取到,调用对应的get方法 对列进行设置值
			StuModel stuModel = list.get(i-1);
			dataRow.createCell(0).setCellValue(stuModel.getStuName());
			dataRow.createCell(1).setCellValue(stuModel.getAge());
			dataRow.createCell(2).setCellValue(stuModel.getSex());
			dataRow.createCell(3).setCellValue(stuModel.getAddress());
		}
		
		//通过repsonse获取输出流
		OutputStream outputStream = response.getOutputStream();
		workBook.write(outputStream);
		
		outputStream.flush();
		outputStream.close();	
		
	}


猜你喜欢

转载自blog.csdn.net/zhaoraolin/article/details/79414563