java中使用POI导出excel文档到指定目录中

工作中遇到一个问题,需要系统定时任务导出excel 文档,然后发送邮件,不是页面的那种导出。于是写了一下。

首先创建需要导出的excel 名称

String fileName = "导出Excel.xlsx"; //创建名称
String rpath = null;
ClassLoader cldr=getClass().getClassLoader();
        if(null!=cldr){
            rpath = cldr.getResource("/").getPath();
        }else{
            rpath="###";
        }
         String os = System.getProperty("os.name");//获取当前操作系统
         if (os != null && os.startsWith("Windows")) {
             if (rpath.startsWith("/")) {
                 rpath = rpath.substring(1, rpath.length());
             }
         }
         if (rpath.contains("WEB-INF")) {
             rpath = rpath.substring(0, rpath.indexOf("WEB-INF")) + "excel";
         }
         String rpathfinal = rpath +"/"+ fileName;//路径
 
        SXSSFWorkbook wb = new SXSSFWorkbook(1024); // 这里1024是在内存中的数量,如果大于此数量时,会写到硬盘,以避免在内存导致内存溢出  
        Sheet sh = wb.createSheet();
for (int i = 0; i < List.size()+1; i++) { 
            sh.setColumnWidth(i,4500);
            Row row = sh.createRow(i);
            if (i==0) {
                row.createCell(0).setCellValue("xxxx");  
                row.createCell(1).setCellValue("aaaa");  
                row.createCell(2).setCellValue("bbbb");  
                row.createCell(3).setCellValue("cccc");  
            }else{
                row.createCell(0).setCellValue(StringUtil.isNullOrEmpty(List.get(i-1).get("belong")));  
                row.createCell(1).setCellValue(StringUtil.isNullOrEmpty(List.get(i-1).get("dqbj")));  
                row.createCell(2).setCellValue(StringUtil.isNullOrEmpty(List.get(i-1).get("datasource")));
                row.createCell(3).setCellValue(StringUtil.isNullOrEmpty(List.get(i-1).get("tablename")));  
            }
        }
        FileOutputStream output=new FileOutputStream(rpathfinal); 
        wb.write(output);
        output.close();
try {
            //发送邮件给指定人
            String EmailMessage = "这是您需要的excel文档,截止时间为:"+ today;
            SendMailUtil.createFileMail(Email, "标题", rpathfinal, EmailMessage);
        } catch (Exception e) {
            e.printStackTrace();
        }    
        //删除存在文件夹中的文档
        LOGGER.info("<------------------开始删除文件:"+fileName);
        boolean deleteFile = DeleteFile(rpathfinal);//删除文件
        LOGGER.info("<------------------删除生成的文件:"+fileName +" 删除结果:"+ deleteFile);
    }

猜你喜欢

转载自www.cnblogs.com/xiaosisong/p/10558182.html