Java创建Excel文件,并将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;
    }

好的,我可以提供一些基本的步骤: 1. 在Java中使用Apache POI库创建Excel文件 2. 使用JavaMail API连接邮箱服务器并创建邮件 3. 将Excel文件作为附件添加到邮件中 4. 设置邮件主题、内容、接收人等信息 5. 发送邮件 以下是一些参考代码: ```java // 1. 创建Excel文件 Workbook workbook = new XSSFWorkbook(); Sheet sheet = workbook.createSheet("Sheet1"); Row row = sheet.createRow(0); row.createCell(0).setCellValue("Hello"); row.createCell(1).setCellValue("World"); FileOutputStream outputStream = new FileOutputStream("example.xlsx"); workbook.write(outputStream); outputStream.close(); // 2. 创建邮件 Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", "smtp.gmail.com"); // 邮箱服务器 props.put("mail.smtp.port", "587"); // 邮箱SMTP端口 Session session = Session.getInstance(props, new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("your-email-address", "your-email-password"); } }); Message message = new MimeMessage(session); message.setFrom(new InternetAddress("your-email-address")); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("recipient-email-address")); message.setSubject("Test Email"); // 3. 添加附件 MimeBodyPart attachmentPart = new MimeBodyPart(); attachmentPart.attachFile(new File("example.xlsx")); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(attachmentPart); // 4. 设置邮件内容、附件等信息 MimeBodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent("This is a test message", "text/html"); multipart.addBodyPart(messageBodyPart); message.setContent(multipart); // 5. 发送邮件 Transport.send(message); ``` 提醒一下,以上示例代码仅供参考,需要自己根据具体情况进行适当的修改和调整。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值