zoukankan      html  css  js  c++  java
  • 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;
            }

    }

     

  • 相关阅读:
    Android开发系列(十七)QQ聊天之Android显示Gif ——在TextView中添加动态表情
    玩转Hook——Android权限管理功能探讨(二)
    玩转Hook——Android权限管理功能探讨(一)
    由一个简单算法想到的程序员素养问题
    Android手机间无线互传功能探索及实现
    从字节码的角度看Java内部类与外部类的互相访问
    HttpClient与HttpUrlConnection下载速度比较
    记一道有趣的Twitter面试题
    Android改进版CoverFlow效果控件
    Android应用如何监听自己是否被卸载及卸载反馈功能的实现(第二版)
  • 原文地址:https://www.cnblogs.com/lwh0206/p/7199402.html
Copyright © 2011-2022 走看看