使用POI导出excel模板浏览器直接下载


		
			org.apache.poi
			poi-scratchpad
			3.0.2-FINAL
		
		
			org.apache.poi
			poi
			3.9
		
		
			org.apache.poi
			poi-examples
			3.9
		
		
			org.apache.poi
			poi-ooxml
			3.9
		
		
			org.apache.poi
			poi-ooxml-schemas
			3.9
		

@RequestMapping("/downloadTaskTemplate")
    @ResponseBody
    public String exportFile(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String businessId = request.getParameter("businessId");
        response.reset();
        try {
            List list = new ArrayList<>();
            if (!StringUtils.isBlank(businessId)) {
                List strres = tBusinessService.getCsvHeaderById(Integer.valueOf(businessId));
                if (null != strres && strres.size() > 0) {
                    list.addAll(strres);
                }
            }
            XSSFWorkbook sheet1 = FileUtil.createExcelFile(list, "sheet1");
            OutputStream output = null;
            try {
                output = response.getOutputStream();
                response.setContentType("application/octet-stream");
                response.setHeader("Content-Disposition",
                        "attachment; filename=" + URLEncoder.encode("call_template.xls", "UTF-8"));
                sheet1.write(output);
                output.flush();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (output != null) {
                    try {
                        output.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return null;
    }

public static XSSFWorkbook createExcelFile(List list, String sheetName)
			throws IllegalArgumentException, IllegalAccessException, ClassNotFoundException {
		// 创建新的Excel工作簿
		XSSFWorkbook workbook = new XSSFWorkbook();
		// 在Excel工作簿中建一工作表,其名为缺省值, 也可以指定Sheet名称
		XSSFSheet sheet = workbook.createSheet(sheetName);
		XSSFRow row = sheet.createRow(0);
		XSSFCell cell = row.createCell(0);
		for (int i = 0; i < list.size(); i++) {
			cell.setCellValue(list.get(i));
			cell = row.createCell(i + 1);
		}
		return workbook;

	}

你可能感兴趣的:(java)