`

java 导出excel

    博客分类:
  • Java
 
阅读更多
    //抑制过时 API的警告,不然有些代码会被打横线
   @SuppressWarnings("deprecation")
	public boolean exportUser() {
		// TODO Auto-generated method stub
		          //   第一步,创建一个webbook,对应一个Excel文件
				try {
					HSSFWorkbook wb = new HSSFWorkbook();
					// 第二步,在webbook中添加一个sheet,对应Excel文件中的sheet
					HSSFSheet sheet = wb.createSheet("用户列表");
					// 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
					HSSFRow row = sheet.createRow((int) 0);
					// 第四步,创建单元格,并设置值表头 设置表头居中
					HSSFCellStyle style = wb.createCellStyle();
					style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式

					HSSFCell cell = row.createCell((short) 0);
					cell.setCellValue("序号");
					cell.setCellStyle(style);
					cell = row.createCell((short) 1);
					cell.setCellValue("登录时间");
					cell.setCellStyle(style);
					cell = row.createCell((short) 2);
					cell.setCellValue("用户手机号码");
					cell.setCellStyle(style);
					cell = row.createCell((short) 3);
					cell.setCellValue("用户名");
					cell.setCellStyle(style);
					cell = row.createCell((short) 4);
					cell.setCellValue("性别");
					cell.setCellStyle(style);
					cell = row.createCell((short) 5);
					cell.setCellValue("城市");
					cell.setCellStyle(style);
					cell = row.createCell((short) 6);
					cell.setCellValue("运营商");
					cell.setCellStyle(style);
					

					// 第五步,写入实体数据 实际应用中这些数据从数据库得到,
					List<Map<String, Object>> list = reportDAO.exportActiveUser();

					int j=1;
					for (Map<String, Object> mapList : list) {
						if(j<=list.size()){
						row = sheet.createRow((short) j);
						String user_id = String.valueOf(mapList.get("user_id"));
						String login_time = (String) mapList.get("login_time");
						String phone = (String) mapList.get("phone");
						String nickname = (String) mapList.get("nickname");
						String sex = (String)mapList.get("sex");
						String pn_areaname = (String) mapList.get("pn_areaname");
						String pn_opername = (String) mapList.get("pn_opername");
						// 第四步,创建单元格,并设置值
						row.createCell((short) 0).setCellValue(user_id);
						row.createCell((short) 1).setCellValue(login_time);
						row.createCell((short) 2).setCellValue(phone);
						row.createCell((short) 3).setCellValue(nickname);
						row.createCell((short) 4).setCellValue(sex);
						row.createCell((short) 5).setCellValue(pn_areaname);
						row.createCell((short) 6).setCellValue(pn_opername);
						j++;
						}
					}
					// 第六步,将文件存到指定位置,这里放到桌面
					 FileSystemView fsv = FileSystemView.getFileSystemView();  
			         String deskpath=fsv.getHomeDirectory().toString();  
			         File file=new File(deskpath+"/用户列表.xls");  
					FileOutputStream fout = new FileOutputStream(file);
					wb.write(fout);
					fout.close();
					return true;
				} catch (IOException e) {
					e.printStackTrace();
					return false;
				}
	}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics