Java往事之《Excel导出数据》

 

Excel导出数据

 下面是个demo,Java实现生成Excel文件  打包成zip,提供下载!

@Controller
@RequestMapping("/importOut/")
public class ImportOutController {

 @RequestMapping(value="excel", method = RequestMethod.POST)  
   public  String  importOut(){

            SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMdd");

            SimpleDateFormat sdf_day = new SimpleDateFormat("yyyy-MM-dd");

            String outPutPath=ServerUtil.UPLOAD_URL+sdf_day.format(new Date())+"\\";//创建临时目录

            createOrder();//调用获取所有订单数据,以及生成Excel文档!

            //打成zip包

           List<File> files = new ArrayList<File>();
                  File Allfile = new File(outPutPath);
                  if (Allfile.exists()) {
                      File[] fileArr = Allfile.listFiles();
                      for (File file2 : fileArr) {
                          files.add(file2);
                      }
                  }

             if(files.size()<1){
                   request.setAttribute("error","没有可导出的文件!");
                   return "importout";
               }

              String fileName = sdf2.format(new Date())+ ".zip";//UUID.randomUUID().toString() + ".zip";
                // 在服务器端创建打包下载的临时文件
                File fileZip = new File(outPutPath + fileName);
                // 文件输出流
                FileOutputStream outStream = new FileOutputStream(fileZip);
                // 压缩流
                ZipOutputStream toClient = new ZipOutputStream(outStream);
                this.zipFile(files, toClient);
                toClient.close();
                outStream.close();
                this.downloadFile(fileZip, response, false,Allfile);

               //清除临时目录以及目录下的文件
                File file = new File(outPutPath);
                deleteDir(file);

                return "importout";

}

 

 

   /**

    *查询全部订单

    */

    private void createOrder(){

               List<OrderInfo> projects =orderService.searchOrderCSV();//调用service层 查询获得所有订单数据
              String sheetName ="玩家订单查询";//定义excel名字
              List<Map<String, String>> listmap = new ArrayList<Map<String, String>>();
              OrderInfo order=null;
              for (int j = 0; j < projects.size(); j++) {//把订单数据集合 转换为 List<Map<String, String>>类型
                  order=projects.get(j);
                  Map<String, String> mapValue = new LinkedHashMap<String, String>();
                  mapValue.put("successTime", Loader.df.format(order.getSuccessTime()));
                  mapValue.put("oid", String.valueOf(order.getOid()));
                  mapValue.put("type",String.valueOf(order.getType()));
                  mapValue.put("num",String.valueOf(order.getNum()));
                  mapValue.put("sendRid",String.valueOf(order.getSendRid()));
                  mapValue.put("rid", String.valueOf(order.getRid()));
                  listmap.add(mapValue);
              }
            String columnNames[]={"时间","订单号","类型","金条数量","发放人ID","玩家ID"};//列名
            String keys[]    =     {"successTime","oid","type","num","sendRid","rid"};//map中的key
            CSVUtils.createCSVFile(listmap,columnNames,keys,sheetName);//调用CSVUtils类中createCSVFile()方法生成excel文件

}

 

        /**
         * 下载文件
         * @param file
         * @param response
         * @param isDelete
         */
        public void downloadFile(File file,HttpServletResponse response,boolean isDelete,File Allfile) {
            try {
                // 以流的形式下载文件。
                BufferedInputStream fis = new BufferedInputStream(new FileInputStream(file.getPath()));
                byte[] buffer = new byte[fis.available()];
                fis.read(buffer);
                fis.close();
                // 清空response
                response.reset();
                OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
                response.setContentType("application/octet-stream");
                response.setHeader("Content-Disposition", "attachment;filename=" + new String(file.getName().getBytes("UTF-8"),"ISO-8859-1"));
                toClient.write(buffer);
                toClient.flush();
                toClient.close();
                if(isDelete)
                {
                    file.delete();        //是否将生成的服务器端文件删除
                    //System.out.println(Allfile.isFile());  
                    if(Allfile.isDirectory()) {  
                         File[] childFilePaths = Allfile.listFiles();  
                         for(File childFile : childFilePaths){    
                             //System.out.println("删除:"+childFile.getName());  
                             childFile.delete();  
                         }    
                    }
                    Allfile.delete();
                }
             }
             catch (IOException ex) {
                ex.printStackTrace();
            }
        }

 

 public void zipFile(List<File> files, ZipOutputStream outputStream) throws IOException, ServletException {
            try {
                int size = files.size();
                // 压缩列表中的文件
                for (int i = 0; i < size; i++) {
                    File file = (File) files.get(i);
                    zipFile(file, outputStream);
                }
            } catch (IOException e) {
                throw e;
            }
        }

 

   private static boolean deleteDir(File dir) {
            if (dir.isDirectory()) {
                String[] children = dir.list();
                 //递归删除目录中的子目录下
                for (int i=0; i<children.length; i++) {
                    boolean success = deleteDir(new File(dir, children[i]));
                    if (!success) {
                        return false;
                    }
                }
            }
            // 目录此时为空,可以删除
            return dir.delete();
        }

 

}

 

public class CSVUtils {

 public static File createCSVFile(List exportData,String columnNames[], String []keys,
               String filename) {

            SimpleDateFormat sdf_day = new SimpleDateFormat("yyyy-MM-dd");
             String outPutPath=ServerUtil.UPLOAD_URL+sdf_day.format(new Date())+"\\";
            File csvFile = null;
            BufferedWriter csvFileOutputStream = null;
            try {
                csvFile = new File(outPutPath + filename + ".csv");
                File parent = csvFile.getParentFile();
                if (parent != null && !parent.exists()) {
                    parent.mkdirs();
                }
                csvFile.createNewFile();

                // GB2312使正确读取分隔符","
                csvFileOutputStream = new BufferedWriter(new OutputStreamWriter(
                        new FileOutputStream(csvFile), "GB2312"), 1024);
                // 写入文件头部
                for(int i=0;i<columnNames.length;i++){
                    csvFileOutputStream.write("\""
                    + columnNames[i].toString() + "\"");
                    csvFileOutputStream.write(",");
                }
                csvFileOutputStream.newLine();
                // 写入文件内容
                for (Iterator iterator = exportData.iterator(); iterator.hasNext();) {
                    Object row = (Object) iterator.next();
                    for(int i=0;i<keys.length;i++){
                        csvFileOutputStream.write("\""
                                + BeanUtils.getProperty(row,keys[i]).toString() + "\"");
                         csvFileOutputStream.write(",");
                    }
                    if (iterator.hasNext()) {
                        csvFileOutputStream.newLine();
                    }
                }
                csvFileOutputStream.flush();
            } catch (Exception e) {
                logger.error("Exception", e);
            } finally {
                try {
                    csvFileOutputStream.close();
                } catch (IOException e) {
                    logger.error("IOException", e);
                }
            }
            return csvFile;
        }

}

 

 

posted @ 2017-07-18 11:10  初见(全栈成长中)  阅读(163)  评论(0编辑  收藏  举报