JAVA Excel 表格数据下载

Excel 下载工具类:

    public HttpServletResponse download(String path, HttpServletResponse response) {
        try {
            // path是指欲下载的文件的路径。
            File file = new File(path);
            // 取得文件名。
            String filename = file.getName();
            // 取得文件的后缀名。
            String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();
            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(path));
            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()));
            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) {
            ex.printStackTrace();
        }
        return response;
    }

数据填充方法:

    @RequestMapping({ "/manage/datastatistical_show.htm" })
    public void datastatistical_show(HttpServletRequest request, HttpServletResponse response) {
        List<DataStatistical> dsList  =    this.dataStatisticalService.query("select obj from DataStatistical obj order by obj.addTime asc", null, -1, -1);
        List<String> header = new ArrayList<String>();
        header.add("用户名");
        header.add("开始时间");
        header.add("结束时间");
        header.add("店铺名称");
        header.add("店员名称");
        header.add("访问内容");
        List<Map> data = new ArrayList<Map>();
                for (DataStatistical ds:dsList) {
                    Map<String, String> map = new HashMap<>();
                    map.put("用户名",   ds.getUser().getUserName());
                    map.put("开始时间", ds.getBeginTime().toString());
                    map.put("结束时间", ds.getEndTime().toString());
                    map.put("店铺名称", (ds.getStore()==null)?null:ds.getStore().getStore_name());
                    map.put("店员名称", (ds.getClerkuser()==null)?null:ds.getClerkuser().getUser().getUserName());
                    map.put("访问内容", ds.getLook_type());
                    data.add(map);
                }
        String path="";
        try {
              String realPath=request.getRealPath("/");
              path=realPath+"/download/"+UUID.randomUUID()+".xls";
            ExcelFileUtils.OutputExcel(path,header, data);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        new OrderSellerAction().download(path, response);
    }

猜你喜欢

转载自blog.csdn.net/qq_40864915/article/details/86524793