文件导出

既然会让用户下载excel文件模板,就会提供用户导出数据为excel

/**
     * 
     * 名称:exportOrgExcel <br/>
     * 描述:导出信息列表 <br/>
     * @param session
     * @param request
     * @param response
     */
    @RequestMapping(value = "exportOrgExcel", produces = {"text/javascript;charset=UTF-8"})
    public void exportOrgExcel(HttpServletRequest request,HttpServletResponse response) {
    
        //这里是导入excel的数据,是list map形式
        List<Map<String,Object>> list=ygxTchOrganizationService.getOrganization(schoolCode);
        //获取上传路径,首先是导出数据到服务器,然后才进行复制操作到本地,这里是根据业务构建的文件夹名称
        String filePath=FileUtils.getSystemPath()+FileUtils.getUploadPath("xls", schoolCode, "school")+"exptmp/";
        File targetFile = new File(filePath);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        //文档保存路径
        String fileName=filePath+"org_"+System.currentTimeMillis();
        
        //生成excel
        ExcelUtils.exportExcelByMap(list, "组织结构", "学院名称,专业名称,班级名称", "dpm_name,maj_name,cls_name",fileName);
        File file=new File(fileName);
        //下载到本地
        FileUtils.download(file, Constants.DEFAULT_ORG_EXPORT_EXCEL_NAME, request, response);
        if(file.exists())file.delete();
        
    }

提供fileUtil工具类

    /**
     * 根据当前操作系统,获得上传路径
     * 
     * @return String
     */
    public static String getSystemPath() {
        String os = System.getProperty("os.name").toLowerCase();
        if (null != os && !"".equalsIgnoreCase(os)) {
            if (os.startsWith("win")) return "C:/home/data";
            else return "/home/data";
        }
        return null;
    }
/**
     * 判断上传文件类型 ,构建不同上传路径
     * 
     * @param suffix
     *            文件类型(参考:Constants.FILE_TYPE)
     * @param id
     *            用户ID | 课程ID | 学校ID
     * @param type
     *            文件所属类型:(参考:Constants.TYPE)
     * @return 上传路径字符串 (调用该方法的所有方法必须 验证所得路径是否为空)
     */
    public static String getUploadPath(String suffix, String id, String type) {
        StringBuilder sb = new StringBuilder();
        String fileSuffixType = null;    //文件逻辑类型
        boolean isContinue = true;    //验证参数是否合法变量
        
        //验证:是否为视频
        if(isContinue){
            for(String str: Constants.videoSuffix){
                if(StringUtils.equalsIgnoreCase(str, suffix)){
                    fileSuffixType = "video";
                    isContinue = false;
                    break;
                }
            }
        }
        
        //验证:是否为图片
        if(isContinue){
            for(String str: Constants.pictureSuffix){
                if(StringUtils.equalsIgnoreCase(str, suffix)){
                    fileSuffixType = "picture";
                    isContinue = false;
                    break;
                }
            }
        }
        
        //验证:是否为Word文件
        if(isContinue){
            for(String str: Constants.wordSuffix){
                if(StringUtils.equalsIgnoreCase(str, suffix)){
                    fileSuffixType = "doc";
                    isContinue = false;
                    break;
                }
            }
        }
        
        //验证:是否为PPT文件
        if(isContinue){
            for(String str: Constants.pptSuffix){
                if(StringUtils.equalsIgnoreCase(str, suffix)){
                    fileSuffixType = "ppt";
                    isContinue = false;
                    break;
                }
            }
        }
        
        //验证:是否为Excl文件
        if(isContinue){
            for(String str: Constants.exclSuffix){
                if(StringUtils.equalsIgnoreCase(str, suffix)){
                    fileSuffixType = "xls";
                    isContinue = false;
                    break;
                }
            }
        }
        
        //验证:是否为压缩文件
        if(isContinue){
            for(String str: Constants.compressSuffix){
                if(StringUtils.equalsIgnoreCase(str, suffix)){
                    fileSuffixType = "zip";
                    isContinue = false;
                    break;
                }
            }
        }
        
        //验证:如果以上文件格式都不存在,则并为other类
        if(isContinue){
            fileSuffixType = "other";
        }
        
        //验证:文件后缀类型是否正确,并构建文件路径
        boolean isFileType = false;
        for(int i=0;i<buildSuffixFolder.length;i++){
            if(buildSuffixFolder[i].equalsIgnoreCase(fileSuffixType)){
                sb.append("/" + buildSuffixFolder[i] + "/");
                isFileType = true;
                break;
            }
        }
        if(!isFileType){
            ExceptionUtils.throwException("上传路径构建异常:参数错误");
            return null;
        }
        
        //验证:文件所属类型是否正确,并构建路径
        boolean isType = false;
        for(int i=0;i<buildLogicFolder.length;i++){
            if(buildLogicFolder[i].equalsIgnoreCase(type)){
                sb.append(buildLogicFolder[i] + "/");
                if(buildLogicFolder[i].equals("user")){
                    sb.append(TimeUtils.getYearMonth()).append("/");    //用户,上传路径加上年月
                }
                isType = true;
                break;
            }
        }
        if(!isType){
            ExceptionUtils.throwException("上传路径构建异常:参数错误");
            return null;
        }
        sb.append(id).append("/");
        return sb.toString();
    }
/**
     * 
     * 名称:download<br/>
     * 描述:文件下载 <br/>
     * 
     * @param file
     *            包含文件完整路径的File对象 ,例如new File("c:/yunlu/sch/123456/a.xls")
     * @param fileName
     *            下载后的文件名
     * @param request
     * @param response
     * @return response
     */
    public static HttpServletResponse download(File file, String fileName,
            HttpServletRequest request, HttpServletResponse response) {
        try {
            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(file));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename="
                    + new String(fileName.getBytes("GBK"), "ISO-8859-1"));
            response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(
                    response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            file.delete();
            ex.printStackTrace();
        }
        return response;
    }

提供excelutil工具类

/**
     * 导出Excel文件 数据源的数据格式为List<Map<String K,String V>>
     * 
     * @param objList
     *            : Excel数据源
     * @param title
     *            : 新建Sheet的名称
     * @param strTitle
     *            : Sheet各列的标题(第一行各列的名称)
     * @param strBody
     *            : Sheet各列的取值方法名(各列的值在objClass中get方法名称)
     * @param outputPath
     *            : Excel文档保存路径
     */
    public static void exportExcelByMap(List<Map<String, Object>> objList,
            String title, String strTitle, String strBody, String outputPath) {
        // 创建工作簿(Excel文件)
        HSSFWorkbook workbook = new HSSFWorkbook();

        // 创建Excel工作簿的第一个Sheet页
        HSSFSheet sheet = workbook.createSheet(title);

        // 创建Sheet页的文件头(第一行)
        createTitle(sheet, strTitle);

        // 创建Sheet页的文件体(后续行)
        String[] strArray = strBody.split(",");
        
        for (int objIndex = 0; objList!=null&&objIndex < objList.size(); objIndex++) {
            Map<String, Object> map = objList.get(objIndex);
            HSSFRow row = sheet.createRow(objIndex + 1);
            for (int i = 0; i < strArray.length; i++) {
                HSSFCell cell = row.createCell(i);
                cell.setCellType(HSSFCell.CELL_TYPE_STRING);
                cell.setCellValue(String.valueOf(map.get(strArray[i])==null?"":map.get(strArray[i])));
            }
        }
        // 保存Excel文件
        saveExcelFile(workbook, outputPath);
    }
原文地址:https://www.cnblogs.com/itliucheng/p/4723767.html