---
title: "java web 导出 下拉 excle"
author: "小色帝"
date: "2018-05-15T17:03:45Z"
tags: []
categories: ["企业架构"]
slug: "java-web-excle"
draft: false
lastmod: "2018-05-15T17:03:45Z"
id: 2422816
url: "https://wangdingxin.iteye.com/blog/2422816"
---

@RequestMapping(value = "/getExportExcel", method = RequestMethod.GET)
	public void test_001_getRequestId(ModelMap model,HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		ServletOutputStream out = null;
//		InputStream in = ClassLoader.getSystemResourceAsStream("template/report.xlsx");
//		File f = new File("/template/report.xlsx");
		// 设置response参数，可以打开下载页面
		response.reset();
		getClass().getClassLoader().getResource("/").getPath();
		response.setContentType("application/msexcel;charset=utf-8");
		XSSFWorkbook wb = new XSSFWorkbook(request.getSession().getServletContext()
				.getResourceAsStream("/template/report.xlsx"));
		try {
			XSSFSheet sheet = wb.getSheetAt(0);
			String handers = { "报表名称", "报表描述", "BI源类型", "BI数据源", "报表所属目录",
					"报表路径", "所属模块", "访问方式", "报表类型", "用户类（多个以逗号隔开）" };
			String downRows = { "2", "3", "7", "8" };
//			if (!storageRootPath.equalsIgnoreCase(System
//					.getProperty("java.io.tmpdir"))) {
//				System.setProperty("java.io.tmpdir", storageRootPath);
//			}
//			log.info("java.io.tmpdir" + System.getProperty("java.io.tmpdir"));
			
			// 表头样式
			XSSFCellStyle style = wb.createCellStyle();
			style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式
			// 字体样式
			XSSFFont fontStyle = wb.createFont();
			fontStyle.setFontName("微软雅黑");
			fontStyle.setFontHeightInPoints((short) 12);
			fontStyle.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
			style.setFont(fontStyle);
			
			XSSFRow rowFirst = sheet.createRow(0);// 第一个sheet的第一行为标题
			// 写标题
			for (int i = 0; i < handers.length; i++) {
				XSSFCell cell = rowFirst.createCell(i); // 获取第一行的每个单元格
				sheet.setColumnWidth(i, 8000); // 设置每列的列宽
				cell.setCellStyle(style); // 加样式
				cell.setCellValue(handers*); // 往单元格里写数据
			}
			
			List<String> downData = new ArrayList<String>();
			if ("true".equals(request.getParameter("mark"))) {
				// 填充bi数据
				List<SourceTypeDTO> bitypelist = manageBIReprotService
						.querySourceType();
				List<String> srtlist = new ArrayList<String>();
				List<String> biTypeList = new ArrayList<String>();
				for (SourceTypeDTO dto : bitypelist) {
					if (dto.getName().indexOf("Pentaho") > -1) {
						String biTypeid = dto.getId();
						srtlist.add(dto.getName());
						biTypeList.add(biTypeid);
					}
					if (dto.getName().indexOf("IBM Cognos") > -1) {
						String biTypeid = dto.getId();
						srtlist.add(dto.getName());
						biTypeList.add(biTypeid);
					}

				}
				String  listarry=new String;
				downData.add(srtlist.toArray(listarry));
				// List<BIReportDTO> bilist=
				// manageBIReprotService.queryAllBiInfoList();
				Map<String, List<String>> map = new HashMap<String, List<String>>();
				map.put("typeListId", biTypeList);
				List<BIReportDTO> bilist = manageBIReprotService
						.queryBiListByListTypeId(map);
				// 释放
				List<String> biNameList = new ArrayList<String>();
				for (BIReportDTO bidto : bilist) {
					biNameList.add(bidto.getBiName());
				}
				
				String  biNameArray = new String;
				downData.add(biNameList.toArray(biNameArray));
				// 添加访问方式
				String accType = { "SSO", "API" };
				downData.add(accType);
				// 报表类型
				List<String> reportTypeNameList = new ArrayList<String>();
				List<ReportType> reporttypelist = memoryReportService
						.getReportTypeNameList();
				for (ReportType type : reporttypelist) {
					reportTypeNameList.add(type.getName());
				}
				String  reportNameArray = new String;
				downData.add(reportTypeNameList.toArray(reportNameArray));
			}else{
				String str1 = new String{ "IBM COGNOS8.4", "IBM COGNOS10.4", "PENTAHO_SAIKU5" };
				String str2 = new String{ "COGNOS 10 TEST","MIS-IT系统BI源", "BI(邮件C8)", "MIS-IT系统BI源（C10）", "Peter+Winter", "	MAS-GROUP-Pentaho5 saiku","ELIS-DAP-Pentaho5 saiku" };
				String str3 = new String{ "SSO", "API"};
				List<String> reportTypeNameList = new ArrayList<String>();
				List<ReportType> reporttypelist = memoryReportService
						.getReportTypeNameList();
				for (ReportType type : reporttypelist) {
					reportTypeNameList.add(type.getName());
				}
				String  reportNameArray = new String;
				downData.add(str1);
				downData.add(str2);
				downData.add(str3);
				downData.add(reportTypeNameList.toArray(reportNameArray));
			}
			for (int r = 0; r < downRows.length; r++) {
				String dlData = downData.get(r);// 获取下拉对象
				int rownum = Integer.parseInt(downRows);
				try {
					
					XSSFDataValidationHelper dvHelper = new XSSFDataValidationHelper(sheet);
					XSSFDataValidationConstraint dvConstraint = (XSSFDataValidationConstraint) dvHelper
							.createExplicitListConstraint(dlData);
					CellRangeAddressList addressList = null;
					XSSFDataValidation validation = null;
					addressList = new CellRangeAddressList(1, 500, rownum, rownum);
					validation = (XSSFDataValidation) dvHelper
							.createValidation(dvConstraint, addressList);
					// 07默认setSuppressDropDownArrow(true);
					if ("true".equals(request.getParameter("mark2"))) {
						 validation.setSuppressDropDownArrow(true);
						 validation.setShowErrorBox(true);
					}
					sheet.addValidationData(validation);
				} catch (Exception e) {
					log.info("添加数据验证错误 ： " + e.getMessage());
					throw e;
				}
			}
			response.setCharacterEncoding("UTF-8");
			response.setContentType("application/msexcel");  
			//2.设置文件头：最后一个参数是设置下载文件名(假如我们叫a.pdf)  
			response.setHeader("Content-Disposition", "attachment;fileName="+java.net.URLEncoder.encode("report.xlsx", "UTF-8"));  
			//通过文件路径获得File对象(假如此路径中有一个download.pdf文件)  

			//3.通过response获取ServletOutputStream对象(out)  
			out = response.getOutputStream();  
			//	 
			wb.write(out);
			out.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != out) {
				out.close();
			}
		}
	}