Administrator
发布于 2023-04-14 / 11 阅读
0
0

一些实用的工具类

excel导出

使用easyexcel,添加依赖

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>easyexcel</artifactId>
    <version>1.1.2-beta5</version>
</dependency>

创建实体类

package com.ruoyi.project.study.excel.model;

import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.metadata.BaseRowModel;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @author lsy
 * @version 1.0.0
 * @Description TODO
 * @createTime 2023年04月10日 08:41:00
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class WriteModel extends BaseRowModel {
    @ExcelProperty(value = "姓名", index = 1)
    private String name;
    @ExcelProperty(value = "地址", index = 2)
    private String address;
    @ExcelProperty(value = "年龄", index = 3)
    private Integer age;
}

编写excel工具类,测试

package com.ruoyi.project.study.excel.util;

import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.event.WriteHandler;
import com.alibaba.excel.metadata.Font;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.metadata.Table;
import com.alibaba.excel.metadata.TableStyle;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.ruoyi.project.study.excel.model.WriteModel;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * @author lsy
 * @version 1.0.0
 * @Description excel工具类 数据量大需在业务层分片处理
 * @createTime 2023年04月10日 08:57:00
 */
public class ExcelUtil {
    //模板数据导出
    public static void export() throws IOException {
        OutputStream out = new FileOutputStream("E:\\test\\easyexcel.xlsx");

        ExcelWriter writer = EasyExcelFactory.getWriter(out);

        Sheet sheet = new Sheet(1, 0, WriteModel.class);

        sheet.setSheetName("第一个sheet");

        writer.write(createModelList(), sheet);

        writer.finish();

        out.close();
    }

    //自定义数据导出
    public static void exportCustom() throws IOException {
        OutputStream out = new FileOutputStream("E:\\test\\custom.xlsx");

        ExcelWriter writer = EasyExcelFactory.getWriter(out);

        Sheet sheet = new Sheet(1, 0);

        sheet.setSheetName("第1个sheet");

        Table table = new Table(1);

        table.setTableStyle(createTableStyle());

        table.setHead(createStringHeader());

        writer.write1(createCustomList(), sheet, table);

        //合并单元格
        //writer.merge();

        writer.finish();

        out.close();
    }

    //创建模板测试数据
    public static List<WriteModel> createModelList() {
        List list = new ArrayList();
        Random random = new Random();
        for (int i = 0; i < 100; i++) {
            WriteModel writeModel = WriteModel.builder().name("sy" + i).address("光电" + i).age(random.nextInt(90) + 10).build();
            list.add(writeModel);
        }
        return list;
    }

    //设置表格样式
    public static TableStyle createTableStyle() {
        TableStyle tableStyle = new TableStyle();
        Font headFont = new Font();
        headFont.setBold(true);
        //字体大小
        headFont.setFontHeightInPoints((short) 12);
        headFont.setFontName("楷体");
        tableStyle.setTableHeadFont(headFont);
        //背景色
        tableStyle.setTableHeadBackGroundColor(IndexedColors.LIGHT_YELLOW);

        Font contentFont = new Font();
        contentFont.setBold(true);
        contentFont.setFontHeightInPoints((short) 12);
        contentFont.setFontName("黑体");
        tableStyle.setTableContentFont(contentFont);

        tableStyle.setTableContentBackGroundColor(IndexedColors.LIGHT_GREEN);
        return tableStyle;
    }

    //表头定义
    public static List<List<String>> createStringHeader() {
        List<List<String>> head = new ArrayList<>();
        List<String> headCoulumn1 = new ArrayList<>();
        List<String> headCoulumn2 = new ArrayList<>();
        List<String> headCoulumn3 = new ArrayList<>();
        List<String> headCoulumn4 = new ArrayList<>();
        List<String> headCoulumn5 = new ArrayList<>();

        headCoulumn1.add("第一列");
        headCoulumn1.add("第一列");
        headCoulumn1.add("第一列");
        headCoulumn2.add("第一列");
        headCoulumn2.add("第一列");
        headCoulumn2.add("第一列");

        headCoulumn3.add("第二列");
        headCoulumn3.add("第二列");
        headCoulumn3.add("第二列");
        headCoulumn4.add("第三列");
        headCoulumn4.add("第三列2");
        headCoulumn4.add("第三列2");
        headCoulumn5.add("第一列");
        headCoulumn5.add("第3列");
        headCoulumn5.add("第4列");

        head.add(headCoulumn1);
        head.add(headCoulumn2);
        head.add(headCoulumn3);
        head.add(headCoulumn4);
        head.add(headCoulumn5);

        return head;
    }

    //创建自定义测试数据
    public static List<List<Object>> createCustomList() {
        List<List<Object>> rows = new ArrayList();
        Random random = new Random();
        for (int i = 0; i < 100; i++) {
            List<Object> row = new ArrayList<>();
            row.add("字符串" + i);
            row.add(1000 + i);
            row.add(100 + i);
            row.add("sy");
            row.add("厦门-鼓浪屿");
            rows.add(row);
        }
        return rows;
    }

    public static void main(String[] args) throws IOException {
        exportCustom();
    }
}

对于复杂格式的excel,可以使用FreeMarker模板配合动态参数填充,这里就不展开了

邮件发送

添加pom依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>

配置邮件服务器等信息,这里使用的qq邮箱,需要登录qq邮件,进入设置,开启smtp授权获取授权码

# Spring配置
spring:
  # 邮件模块
  mail:
    host: smtp.qq.com #发送邮件的服务器,这里使用的 QQ 邮件
    username: 邮箱地址
    password: 授权码
    properties:
      mail:
        smtp:
          auth: true
          starttls:
            enable: true
    default-encoding: utf-8

编写工具类

package com.ruoyi.project.study.mail.service;

import org.springframework.mail.SimpleMailMessage;

/**
 * @author lsy
 * @version 1.0.0
 * @Description TODO
 * @createTime 2023年04月08日 16:21:00
 */
public interface MailService {
    /**
     * 发送简单文本的邮件
     *
     * @param to
     * @param subject
     * @param content
     * @return
     */
    boolean send(String to, String subject, String content);

    /**
     * 发送html的邮件
     *
     * @param to
     * @param subject
     * @param html
     * @return
     */
    boolean sendWithHtml(String to, String subject, String html);

    /**
     * 发送带有图片的html的邮件
     *
     * @param to
     * @param subject
     * @param html
     * @param cids
     * @param filePaths
     * @return
     */
    boolean sendWithImageHtml(String to, String subject, String html, String[] cids, String[] filePaths);

    /**
     * 发送带有附件的邮件
     *
     * @param to
     * @param subject
     * @param content
     * @param filePaths
     * @return
     */
    boolean sendWithImageHtml(String to, String subject, String content, String[] filePaths);
}
package com.ruoyi.project.study.mail.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.internet.MimeMessage;

/**
 * @author lsy
 * @version 1.0.0
 * @Description TODO
 * @createTime 2023年04月08日 16:23:00
 */
@Service
public class MailServiceImpl implements MailService {
    private final static Logger logger = LoggerFactory.getLogger(MailServiceImpl.class);

    @Autowired
    private MailProperties mailProperties;
    @Autowired
    private JavaMailSender javaMailSender;

    @Override
    public boolean send(String to, String subject, String content) {
        logger.info("## Ready to send mail ...");
        SimpleMailMessage message = new SimpleMailMessage();
        //邮件发送来源
        message.setFrom(mailProperties.getUsername());
        //邮件发送目标
        message.setTo(to);
        //设置标题
        message.setSubject(subject);
        //设置内容
        message.setText(content);
        try {
            //发送
            javaMailSender.send(message);
            logger.info("send mail success ...");
        } catch (Exception e) {
            logger.error("send mail error: ", e);
            return false;
        }
        return true;
    }

    @Override
    public boolean sendWithHtml(String to, String subject, String html) {
        logger.info("## Ready to send mail ...");
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper mimeMessageHelper = null;
        try {
            mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
            // 邮件发送来源
            mimeMessageHelper.setFrom(mailProperties.getUsername());
            // 邮件发送目标
            mimeMessageHelper.setTo(to);
            // 设置标题
            mimeMessageHelper.setSubject(subject);
            // 设置内容,并设置内容 html 格式为 true
            mimeMessageHelper.setText(html, true);
            javaMailSender.send(mimeMessage);
            logger.info("## Send the mail with html success ...");
        } catch (Exception e) {
            logger.error("Send html mail error: ", e);
            return false;
        }
        return true;
    }

    @Override
    public boolean sendWithImageHtml(String to, String subject, String html, String[] cids, String[] filePaths) {
        logger.info("## Ready to send mail ...");
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper mimeMessageHelper = null;
        try {
            mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
            // 邮件发送来源
            mimeMessageHelper.setFrom(mailProperties.getUsername());
            // 邮件发送目标
            mimeMessageHelper.setTo(to);
            // 设置标题
            mimeMessageHelper.setSubject(subject);
            // 设置内容,并设置内容 html 格式为 true
            mimeMessageHelper.setText(html, true);
            // 设置 html 中内联的图片
            for (int i = 0; i < cids.length; i++) {
                FileSystemResource file = new FileSystemResource(filePaths[i]);
                // addInline() 方法 cid 需要 html 中的 cid (Content ID) 对应,才能设置图片成功,
                mimeMessageHelper.addInline(cids[i], file);
            }
            javaMailSender.send(mimeMessage);
            logger.info("## Send the mail with image success ...");
        } catch (Exception e) {
            logger.error("Send html mail error: ", e);
            return false;
        }
        return true;
    }

    @Override
    public boolean sendWithImageHtml(String to, String subject, String content, String[] filePaths) {
        logger.info("## Ready to send mail ...");
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper mimeMessageHelper = null;
        try {
            mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
            // 邮件发送来源
            mimeMessageHelper.setFrom(mailProperties.getUsername());
            // 邮件发送目标
            mimeMessageHelper.setTo(to);
            // 设置标题
            mimeMessageHelper.setSubject(subject);
            // 设置内容
            mimeMessageHelper.setText(content);
            // 添加附件
            for (int i = 0; i < filePaths.length; i++) {
                FileSystemResource file = new FileSystemResource(filePaths[i]);
                String attachementFileName = "附件" + (i + 1);
                mimeMessageHelper.addAttachment(attachementFileName, file);
            }
            javaMailSender.send(mimeMessage);
            logger.info("## Send the mail with enclosure success ...");
        } catch (Exception e) {
            logger.error("Send html mail error: ", e);
            return false;
        }
        return true;
    }
}
package com.ruoyi.project.study.mail.controller;

import com.ruoyi.project.study.mail.service.MailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author lsy
 * @version 1.0.0
 * @Description TODO
 * @createTime 2023年04月08日 16:30:00
 */
@RestController
@RequestMapping("/study/mail")
public class MailController {
    @Autowired
    private MailService mailService;

    @RequestMapping("send")
    public Object send() {
        String to = "接受者邮箱";
        String subject = "测试邮件";
        String content = "测试内容。。。。。。。。。";
        return mailService.send(to, subject, content);
    }
}

 


评论