当前位置:   article > 正文

Java创建Excel文件,并将excel作为附件邮件发送_java发送邮件带excel附件

java发送邮件带excel附件

仅供参考部分方法,无法直接使用。

// 报表临时文件目录
public static final String WORK_FILES = excelTask.class.getResource("/").getPath() + "workfiles/";
   /**
     * 邮件定时发送excel报表
     */
    public void sendInfoExcel() {
        try {
            String nowTime = DateUtil.getStringDate();
            String beginTime = "xxxx";
            String finishTime = "xxxx";
            reportQO.setBeginDate(beginTime);
            reportQO.setEndDate(finishTime);
            //查询报表信息
            List<WorkInfo> WorkInfos = reportDao.countLogData(reportQO);
            if(StringTool.isNotEmpty(WorkInfos) && WorkInfos.size() > 0){
                // 创建新报表文件
                String fileName = "excel报表.xls";
                String fileFullPath = WORK_FILES + fileName;
                //删除之前的报表文件
                this.deleteFile(fileFullPath);
                // 生成excel文件
                OutputStream out = null;
                try {
                    File file = new File(fileFullPath);
                    if (!file .getParentFile().exists()) {
                        file .getParentFile().mkdirs();
                    }
                    if(!file .exists()) {
                        file .createNewFile();
                    }
                    out = new FileOutputStream(file);
                    //报表信息
                    String[] fields = {"项目名称", "产品名称", "投入数", "产出数"};
                    SXSSFWorkbook wb = exportInfoExcel(WorkInfos, null, 0, fields, nowTime); //第1页查询结束(第一次查询)
                    wb.write(out);
                    out.flush();
                    out.close();
                    logger.info("生成报表 成功");
                } catch (Exception e) {
                    logger.debug("生成报表异常" + e.getMessage());
                    e.printStackTrace();
                    try {
                        out.close();
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                }
                WarnMesssgeData warnMes = new WarnMesssgeData();
                //邮件标题
                warnMes.setSubject("每日报表");
                //邮件内容
                warnMes.setContent("报表见附件(更新时间:"+ nowTime +")");
                //文件名称
                warnMes.setFileName(fileName);
                //文件地址
                warnMes.setFileAddress(fileFullPath);
                //发送邮件
                this.sendExcelEmail(warnMes);
            }
        } catch (Exception e) {
            logger.error("邮件定时发送excel报表发生异常", e);
        }
    }
/**
     * 发送邮件设置
     * @param warnMes
     * @throws GeneralSecurityException
     * @throws Exception
     */
    public static void sendExcelEmail(WarnMesssgeData warnMes) throws GeneralSecurityException, Exception {
        Properties prop = new Properties();
        // 开启debug调试,以便在控制台查看
        prop.setProperty("mail.debug", "true");
        // 设置邮件服务器主机名
        prop.setProperty("mail.host", "smtp.exmail.qq.com");
        // 发送服务器需要身份验证
        prop.setProperty("mail.smtp.auth", "true");
        // 发送邮件协议名称
        prop.setProperty("mail.transport.protocol", "smtp");
        //端口
        prop.setProperty("mail.smtp.port", "465");
        // 开启SSL加密,否则会失败
        MailSSLSocketFactory sf = new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        prop.put("mail.smtp.ssl.enable", "true");
        prop.put("mail.smtp.ssl.socketFactory", sf);
        // 创建session
        Session session = Session.getInstance(prop);
        // 通过session得到transport对象
        Transport ts = session.getTransport();
        // 连接邮件服务器:邮箱类型,帐号,授权码代替密码(更安全)
        ts.connect("smtp.exmail.qq.com","test1@qq.com", "111111");
        // 创建邮件
        InternetAddress[] receiverArr={new InternetAddress("test1@qq.com"),new InternetAddress("test2@qq.com")};
        javax.mail.Message message = createExcelMail(session,receiverArr,warnMes);
        // 发送邮件
        ts.sendMessage(message, message.getAllRecipients());
        ts.close();
    }

    /**
     * 发送邮件
     * @param session
     * @param receiverArr
     * @param warnMes
     * @return
     * @throws Exception
     */
    public static MimeMessage createExcelMail(Session session, InternetAddress[] receiverArr, WarnMesssgeData warnMes) throws Exception  {
        // 创建邮件对象
        MimeMessage message = new MimeMessage(session);
        // 指明邮件的发件人
        message.setFrom(new InternetAddress("test1@qq.com"));
        // 指明邮件的收件人,现在发件人和收件人是一样的,那就是自己给自己发
        message.setRecipients(javax.mail.Message.RecipientType.TO, receiverArr);
        // 邮件的标题
        message.setSubject(warnMes.getSubject());
        // 设置邮件消息内容、包含附件
        Multipart msgPart = new MimeMultipart();
        message.setContent(msgPart);

        MimeBodyPart body = new MimeBodyPart();   // 正文
        MimeBodyPart attach = new MimeBodyPart(); // 附件
        msgPart.addBodyPart(body);
        msgPart.addBodyPart(attach);

        // 设置正文内容
        body.setContent(warnMes.getContent(), "text/html;charset=utf-8");
        // 设置附件内容
        attach.setDataHandler(new DataHandler(new FileDataSource(warnMes.getFileAddress())));
        attach.setFileName((MimeUtility.encodeText(warnMes.getFileName())));

        message.saveChanges();

        // 邮件的创建时间
        message.setSentDate(new Date());
        // 返回创建好的邮件对象
        return message;
    }
/**
 * 删除单个文件
 *
 * @param fileName 要删除的文件的文件名
 * @return 单个文件删除成功返回true,否则返回false
 */
public static boolean deleteFile(String fileName) {
    File file = new File(fileName);
    // 如果文件路径所对应的文件存在,并且是一个文件,则直接删除
    if (file.exists() && file.isFile()) {
        if (file.delete()) {
            System.out.println("删除单个文件" + fileName + "成功!");
            return true;
        } else {
            System.out.println("删除单个文件" + fileName + "失败!");
            return false;
        }
    } else {
        System.out.println("删除单个文件失败:" + fileName + "不存在!");
        return false;
    }
}
 private SXSSFWorkbook exportInfoExcel(List<WorkInfo> WorkInfos, SXSSFWorkbook workbook, int index, String[] fields, String nowTime) {
        Sheet sheet;
        if (index == 0) {
            if (StringTool.isEmpty(workbook)) {
                workbook = new SXSSFWorkbook();
            }
            sheet = workbook.createSheet("excel报表");
            // 生成一个样式
            CellStyle style = workbook.createCellStyle();
            // 设置背景色
//            style.setFillForegroundColor(HSSFColor.LIGHT_TURQUOISE.index);
//            style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);

            //设置边框居中
            style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
            style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
            style.setBorderRight(HSSFCellStyle.BORDER_THIN);
            style.setBorderTop(HSSFCellStyle.BORDER_THIN);
            style.setAlignment(HSSFCellStyle.ALIGN_CENTER);

            // 设置字体
            Font font = workbook.createFont();
            font.setFontName("仿宋_GB2312");
            font.setColor(HSSFColor.OLIVE_GREEN.index);
            font.setFontHeightInPoints((short) 18);
            font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
            // 把字体应用到当前的样式
            style.setFont(font);

            Row row1 = sheet.createRow(0);
            row1.setHeightInPoints(25);
            Cell cell = row1.createCell(0);
            String titleInfo = "报表信息(更新时间:"+ nowTime +")";
            cell.setCellValue(titleInfo);
            cell.setCellStyle(style);
            int colLength = fields.length;
            for (int i = 1; i < colLength; i++) {
                cell = row1.createCell(i);
                cell.setCellStyle(style);
            }
            sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, colLength - 1));

            // 生成一个样式
            CellStyle style1 = workbook.createCellStyle();
            // 设置背景色
            style1.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
            style1.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);

            //设置边框
            style1.setBorderBottom(HSSFCellStyle.BORDER_THIN);
            style1.setBorderLeft(HSSFCellStyle.BORDER_THIN);
            style1.setBorderRight(HSSFCellStyle.BORDER_THIN);
            style1.setBorderTop(HSSFCellStyle.BORDER_THIN);
            style1.setAlignment(HSSFCellStyle.ALIGN_CENTER);


            // 设置字体
            Font font1 = workbook.createFont();
            font1.setFontName("仿宋_GB2312");
            font1.setColor(HSSFColor.OLIVE_GREEN.index);
            font1.setFontHeightInPoints((short) 14);
            font1.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
            // 把字体应用到当前的样式
            style1.setFont(font1);
            sheet.setColumnWidth(0, 5000);
            sheet.setColumnWidth(1, 5000);
            sheet.setColumnWidth(2, 5000);
            sheet.setColumnWidth(3, 5000);


            //生成一行
            Row row2 = sheet.createRow(1);
            Cell cell1;
            for (int k = 0; k < fields.length; k++) {
                cell1 = row2.createCell(k);
                cell1.setCellValue(fields[k]);
                cell1.setCellStyle(style1);
            }
        }

        sheet = workbook.getSheetAt(0);
        // 生成一个样式
        CellStyle style3 = workbook.createCellStyle();

        //设置边框
        style3.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        style3.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        style3.setBorderRight(HSSFCellStyle.BORDER_THIN);
        style3.setBorderTop(HSSFCellStyle.BORDER_THIN);
        style3.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        style3.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);//垂直居中

        Font font3 = workbook.createFont();
        font3.setFontName("仿宋_GB2312");
        font3.setColor(HSSFColor.BLACK.index);
        font3.setFontHeightInPoints((short) 10);
        font3.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        // 把字体应用到当前的样式
        style3.setFont(font3);
        style3.setWrapText(true);


        if (WorkInfos == null || WorkInfos.size() == 0) {
            return workbook;
        }

        Row row3;
        Cell cell1;
        int contentIndex = 2;
        int count = 0;
        for (int i = 0; i < WorkInfos.size()-1; i++) {
            WorkInfo bean = WorkInfos.get(i);
           
            row3 = sheet.createRow( contentIndex + i + count);

            cell1 = row3.createCell(0);
            cell1.setCellValue(bean.getSysName());
            cell1.setCellStyle(style3);

            cell1 = row3.createCell(1);
            cell1.setCellValue(bean.getProdName());
            cell1.setCellStyle(style3);

            cell1 = row3.createCell(2);
            cell1.setCellValue(bean.getTotalNum());
            cell1.setCellStyle(style3);

            cell1 = row3.createCell(3);
            cell1.setCellValue(bean.getFinalNum());
            cell1.setCellStyle(style3);

        }

        return workbook;
    }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Cpp五条/article/detail/591903
推荐阅读
相关标签
  

闽ICP备14008679号