1. 程式人生 > >java後臺Controller下載檔案方法

java後臺Controller下載檔案方法

   /**
     * 匯出
     * @param request
     * @param response
     */
    @RequestMapping(value="exportInfo")
    public void exportInfo(HttpServletRequest request,HttpServletResponse response ){
        try {
            String[] fi_ids={"0001","0002"};

            //根據業務查詢需要下載的資訊
            List<Map<String, Object>> selectExportInfo = backgroundService.selectExportInfo(fi_ids);
            String file_name=System.currentTimeMillis()+"";
            String fileDir="E:"+File.separator+"upload"+File.separator+file_name+".xls";
            String sheetName="資訊";
            //String[] titleRow={"企業名稱","核心聯絡人","狀態","類別"};
            String[] title={"name","cc_name","state","fi_tpye"};
            ExcelUtils2.createExcel_OneSheet

(fileDir, sheetName, title);
            ExcelUtils2.writeToExcel_OneSheet(fileDir, sheetName, selectExportInfo, title);
            
            String fileName=fileDir.substring(fileDir.lastIndexOf("/")+1);
            byte[] buffer=null;  
            buffer = ExcelUtils.downFileByte
(fileDir) ; 
            String fileSuffixName=   fileName.substring(fileName.lastIndexOf(".")+1);
            response.reset(); //清除快取
            response.setContentType("application/" +fileSuffixName + ";" +"charset = UTF-8"); //設定字符集和檔案字尾名
            String name="匯出資訊";
            name = new String(name.getBytes(), "ISO-8859-1");
            response.setHeader("Content-Disposition","attachment; filename=" +name+"."+fileSuffixName); // 設定檔名稱
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());  
            toClient.write(buffer);  
            toClient.flush();  
            toClient.close();
        } catch (Exception e) {
            e.printStackTrace();
            Log4jUtil.getLog4jUtil().error("匯出資訊異常"+e.getMessage());
        }
    }

/**
     * 建立一個新excel.  一個sheet
     * 
     * @param fileDir
     *            excel的路徑
     * @param sheetName
     *            要建立的表格索引
     * @param titleRow
     *            excel的第一行即表格頭
     */
    public static void createExcel_OneSheet(String fileDir, String sheetName, String titleRow[]) throws Exception {
        // 建立workbook
        workbook = new HSSFWorkbook();
        // 新增Worksheet(不新增sheet時生成的xls檔案開啟時會報錯)
        HSSFSheet sheet1 = workbook.createSheet(sheetName);
        // 新建檔案
        FileOutputStream out = null;
        try {
            // 新增表頭
            HSSFRow row = workbook.getSheet(sheetName).createRow(0); // 建立第一行
            for (short i = 0; i < titleRow.length; i++) {
                HSSFCell cell = row.createCell(i);
                cell.setCellValue(titleRow[i]);
            }
            out = new FileOutputStream(fileDir);
            workbook.write(out);
        } catch (Exception e) {
            throw e;
        } finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

 

/**
     * 往excel中寫入(已存在的資料無法寫入).
     * 
     * @param fileDir
     *            檔案路徑
     * @param sheetName 
     *            表格索引
     * @param mapList 
     *            需要寫入的資料
     * @param titleRow[]
     *            excel的第一行即表格頭
     * @throws Exception
     */
    public static void writeToExcel_OneSheet(String fileDir, String  sheetName, List<Map<String, Object>> mapList,String titleRow[]) throws Exception {
        OutputStream out = null;
        // 建立workbook
        File file = new File(fileDir);
        Workbook workBook = getWorkbok(file);
        Sheet sheet = workBook.getSheet(sheetName);
        // 刪除原有資料,除了屬性列
        int rowNumber = sheet.getLastRowNum(); // 第一行從0開始算
        Row row0 = sheet.getRow(0);
        for (int i = 1; i <= rowNumber; i++) {
            Row row = sheet.getRow(i);
            sheet.removeRow(row);
        }
        // 往Excel中寫新資料
        for (int j = 0; j < mapList.size(); j++) {
            // 建立一行:從第二行開始,跳過屬性列
            Row row = sheet.createRow(j + 1);
            Map<String, Object> dataMap = mapList.get(j);
            System.out.println(dataMap);
            int count = row0.getLastCellNum(); 
            for (int k = 0; k <count; k++) {
                for (int i = 0; i < titleRow.length; i++) {
                    Cell cell = row.createCell(k);
                    if (dataMap.get(titleRow[k])!=null) {
                        cell.setCellValue(dataMap.get(titleRow[k]).toString());
                    }
                }
            }
        }
        // 建立檔案輸出流,準備輸出電子表格:這個必須有,否則你在sheet上做的任何操作都不會有效
        out = new FileOutputStream(fileDir);
        workBook.write(out);
    }

/** 
     * 下載檔案 
     * 返回byte[] 
     * @param fileName 需要下載的檔名 
     * @return 
     * @throws Exception 
     */  
    public static byte[] downFileByte(String downLoadPath) throws Exception{  
        byte[] return_arraybyte=null;  
        InputStream ins=new FileInputStream(downLoadPath );  
        ByteArrayOutputStream byteOut = new ByteArrayOutputStream();  
        byte[] buf = new byte[1024];  
        int bufsize = 0;  
        while ((bufsize = ins.read(buf, 0, buf.length)) != -1) {  
            byteOut.write(buf, 0, bufsize);  
        }  
        return_arraybyte = byteOut.toByteArray();  
        byteOut.close();  
        ins.close();  
    return return_arraybyte;  
    }

 

   /**
     *  根據業務查詢需要下載的資訊
     * @param fi_ids
     * @return
     * @throws Exception
     */

    @Override
    public List<Map<String, Object>> selectExportInfo(String[] fi_ids) throws Exception {
        String join = StringUtils.join(fi_ids, ",");
        List<Map<String, Object>> queryForList = jdbcTemplate.queryForList(" SELECT f.name,c.cc_name,f.state,f.fi_tpye from tb_firm_info  f LEFT JOIN tb_industry_commerce i on f.fi_id=i.fi_id LEFT JOIN (SELECT * from tb_core_contacts GROUP BY fi_id) c on f.fi_id=c.fi_id where FIND_IN_SET(f.fi_id,'"+join+"') ");
           return queryForList;
    }