java查询数据库数据放到Excel下载

//参考自这里(https://blog.csdn.net/szl13722587073/article/details/78663076)
public class DownPOIUtils {
	 
	/**
	 * 
	 * @param response:响应对象,类型是HttpServletResponse
	 * @param map:要封装的信息的map容器,其中key为Student,value为String类型的,在这里代表分数
	 * @throws Exception:代表异常对象
	 */
	public static void downPoi(HttpServletResponse response,Map<Student, String> map) throws Exception {
		String fname = "detial" + getTimeStamp();// Excel文件名
		OutputStream os = response.getOutputStream();// 取得输出流
		response.reset();// 清空输出流
		response.setHeader("Content-disposition", "attachment; filename="
				+ fname + ".xls"); // 设定输出文件头,该方法有两个参数,分别表示应答头的名字和值。
		response.setContentType("application/msexcel");
		try {
			new DownPOIUtils().new POIS().createFixationSheet(os, map);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
 
	/**
	 * 该方法用来产生一个时间字符串(即:时间戳)
	 * @return
	 */
	public static String getTimeStamp() {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:MM:ss");
		Date date = new Date();
		return dateFormat.format(date);
	}
	
class POIS {
		public void createFixationSheet(OutputStream os,Map<Student, String> student) throws Exception {
			// 创建工作薄
			HSSFWorkbook wb = new HSSFWorkbook();
			// 在工作薄上建一张工作表
			HSSFSheet sheet = wb.createSheet();
			HSSFRow row = sheet.createRow((short) 0);
			sheet.createFreezePane(0, 1);
			cteateCell(wb, row, (short) 0, "学号");
			cteateCell(wb, row, (short) 1, "姓名");
			cteateCell(wb, row, (short) 2, "性别");
			cteateCell(wb, row, (short) 3, "班级");
			cteateCell(wb, row, (short) 4, "分数");
			int i = 0;
			Set<Student> keySet = student.keySet();
			Iterator<Student> iterator = keySet.iterator();
			while (iterator.hasNext()) {
				HSSFRow rowi = sheet.createRow((short) (++i));
				Student student2 = iterator.next();
				for (int j = 0; j < 4; j++) {
					cteateCell(wb, rowi, (short) 0, student2.getId());
					cteateCell(wb, rowi, (short) 1, student2.getName());
					cteateCell(wb, rowi, (short) 2, student2.getSex());
					cteateCell(wb, rowi, (short) 3, student2.getGrade());
					cteateCell(wb, rowi, (short) 4, student.get(student2));
				}
			}
			wb.write(os);
			os.flush();
			os.close();
			System.out.println("文件生成");
 
		}
 
		@SuppressWarnings("deprecation")
		private void cteateCell(HSSFWorkbook wb, HSSFRow row, short col,String val) {
			HSSFCell cell = row.createCell(col);
			cell.setCellValue(val);
			HSSFCellStyle cellstyle = wb.createCellStyle();
			cellstyle.setAlignment(HSSFCellStyle.ALIGN_CENTER_SELECTION);
			cell.setCellStyle(cellstyle);
		}
	}
}
//自己的逻辑处理————————>页面按钮
<li onclick="printMonthOrder()" style="background-color: #db9907;"><span class="btn_insert">导出Excel</span></li>
//js
function printMonthOrder(){
	var type=$("#type").textbox('getValue');
	var orgId=$("#orgId").textbox('getValue');
	var beginDT=$("#beginDT").textbox('getValue')==""?null:$("#beginDT").textbox('getValue');
	var endDT=$("#endDT").textbox('getValue')==""?null:$("#endDT").textbox('getValue');
	var userId=$("#userId").textbox('getValue')==""?null:$("#userId").textbox('getValue');
	window.location.href = _ctx+"/rest/checkorder/DownloadExcel/"+type+"/"+orgId+"/"+beginDT+"/"+endDT+"/"+userId;
}
//Controller
@Controller
@RequestMapping("checkorder")
public class CheckOrderController extends BaseController {
@RequestMapping(value="DownloadExcel/{type}/{orgId}/{beginDT}/{endDT}/{userId}")
@ResponseBody
public void DownloadExcel(HttpServletRequest request,HttpServletResponse response,@PathVariable() Integer type,@PathVariable() String orgId,
			@PathVariable() String beginDT,@PathVariable() String endDT,@PathVariable() String userId) throws Exception{
		//获取表头列表
		List<Maxterms> titleList = manager.findForColumns(type);
		//获取表格内容列表
		List<MonthSort> sorts =  manager.getByMonthAndUser(beginDT.equals("null")?null:beginDT,endDT.equals("null")?null:endDT, 
				orgId, type,userId.equals("null")?null:userId);
		DownPOIUtils.downPoi(response, titleList,sorts);
	}
}
//下载公用方法
public class DownPOIUtils {
	 
	/**
	 * 
	 * @param response:响应对象,类型是HttpServletResponse
	 * @param map:要封装的信息的map容器,其中key为Student,value为String类型的,在这里代表分数
	 * @throws Exception:代表异常对象
	 */
	public static void downPoi(HttpServletResponse response,List<Maxterms> titleList,List<MonthSort> sorts) throws Exception {
		String fname = "MonthOrder" + getTimeStamp();// Excel文件名
		OutputStream os = response.getOutputStream();// 取得输出流
		response.reset();// 清空输出流
		response.setHeader("Content-disposition", "attachment; filename="
				+ fname + ".xls"); // 设定输出文件头,该方法有两个参数,分别表示应答头的名字和值。
		response.setContentType("application/msexcel");
		try {
			new DownPOIUtils().new POIS().createFixationSheet(os, titleList,sorts);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
 
	/**
	 * 该方法用来产生一个时间字符串(即:时间戳)
	 * @return
	 */
	public static String getTimeStamp() {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = new Date();
		return dateFormat.format(date);
	}
	
class POIS {
		public void createFixationSheet(OutputStream os,List<Maxterms> titleList,List<MonthSort> sorts) throws Exception {
			// 创建工作薄
			HSSFWorkbook wb = new HSSFWorkbook();
			// 在工作薄上建一张工作表
			HSSFSheet sheet = wb.createSheet();
			//设置列宽,第一个参数代表列id(从0开始),第2个参数代表宽度值
			//从第四列开始,设置宽度
			for(int i = 3;i<titleList.size()+3;i++){
				sheet.setColumnWidth(i, 4000); 
			}
			HSSFRow row = sheet.createRow((short) 0);
			sheet.createFreezePane(0, 1);
			//构建表头
			cteateCell(wb, row, (short) 0, "姓名");
			cteateCell(wb, row, (short) 1, "职务");
			cteateCell(wb, row, (short) 2, "日期");
			for(int i = 3;i<titleList.size()+3;i++){
				cteateCell(wb, row, (short)i, titleList.get(i-3).getCheckMaxterm().getName()+titleList.get(i-3).getType());
			}
			cteateCell(wb, row, (short)(titleList.size()+3), "得分");
			//构建表内容
			for(int i=0;i<sorts.size();i++){
				if(sorts.get(i)!=null){
					MonthSort monthSort = sorts.get(i);
					HSSFRow rowi = sheet.createRow((short)i+1);
					cteateCell(wb, rowi, (short) 0, monthSort.getUser().getUsername());
					cteateCell(wb, rowi, (short) 1, monthSort.getUser().getDescription());
					cteateCell(wb, rowi, (short) 2, monthSort.getDate());
					List<UserSortForMaxterm> item = monthSort.getUserSorts();
					for(int j =0;j<item.size();j++){
						if(item.get(j).getOrders()==null){
							cteateCell(wb, rowi, (short)(j+3),"/");
						}else{
							List<CheckOrderVo> vo = item.get(j).getOrders();
							String s = "";
							for(CheckOrderVo voi:vo){
								s += voi.getCheckItem().getItem()+"("+voi.getCheckItem().getSort()+")分。";
							}
							cteateCell(wb, rowi, (short)(j+3),s);
						}
					}
					cteateCell(wb, rowi, (short)(item.size()+3), monthSort.getSort());
				}
			}
			wb.write(os);
			os.flush();
			os.close();
			System.out.println("文件生成");
 
		}
 
		@SuppressWarnings("deprecation")
		private void cteateCell(HSSFWorkbook wb, HSSFRow row, short col,String val) {
			HSSFCell cell = row.createCell(col);
			cell.setCellValue(val);
			//HSSFCellStyle cellstyle = wb.createCellStyle();
			//设置居中(由于居中导致剧中效果部分失效,未找到相应处理办法,暂时注释掉)
			//cellstyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
			//设置自动换行
			//cellstyle.setWrapText(true);
			//cell.setCellStyle(cellstyle);
		}
	}
}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值