1. 程式人生 > >java讀取資料庫中的資料並存儲到excel中去

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();	
		
	}