Java-实用工具类

237 阅读2分钟

邮件发送工具类

package com.chinasoft.hilink.util;


import com.chinasoft.hilink.bean.PushStrategyPO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.*;
import java.util.Properties;


@Component
public class SendEmailUtil {

    @Value("${mail.transport.protocol}")
    private  String protocol;

    @Value("${mail.smtp.host}")
    private  String host;

    @Value("${mail.smtp.port}")
    private  int port;
    @Value("${mail.smtp.auth}")
    private  String auth;

    @Value("${mail.smtp.ssl.enable}")
    private  String sslEnable;

    @Value("${mail.debug}")
    private  String debug;

    @Value("${mail.send.from}")
    private  String from;

    @Value("${mail.smtp.server.user}")
    private  String user;

    @Value("${mail.smtp.server.password}")
    private  String password;



    private static final Logger logger = LoggerFactory.getLogger(SendEmailUtil.class);

    public  boolean send(PushStrategyPO pushStrategyPO, String path, String fileName) {
        Properties properties = new Properties();
        properties.put("mail.transport.protocol", protocol);//协议
//        properties.put("mail.smtp.host","smtp.qq.com");//主机名
        properties.put("mail.smtp.host", host);
        properties.put("mail.smtp.port", port);//端口号
        properties.put("mail.smtp.auth",auth );
        properties.put("mail.smtp.ssl.enable",sslEnable);//设置ssl安全连接
        properties.put("mail.debug", debug);//显示debug信息

        try {
            //会话对象
            Session session = Session.getInstance(properties);
            //获取邮件对象
            Message message = new MimeMessage(session);
            //设置发件人邮箱地址
            message.setFrom(new InternetAddress(from));
            //设置收件人邮箱地址
            String recipient = pushStrategyPO.getRecipient();
            InternetAddress[] internetAddresses1 = buildArray(recipient);
            message.setRecipients(Message.RecipientType.TO, internetAddresses1
            );

            String cc = pushStrategyPO.getCC();
            //设置抄送人邮箱地址
            if (!StringUtils.isEmpty(cc)) {
                InternetAddress[] internetAddresses = buildArray(cc);
                message.setRecipients(Message.RecipientType.CC, internetAddresses);
            }
            //设置邮件标题
            message.setSubject(pushStrategyPO.getSubmit());
            MimeBodyPart mimeBodyPart = new MimeBodyPart();
            mimeBodyPart.setContent(pushStrategyPO.getContent(), "text/html;charset=utf-8");
            //设置附件
            MimeBodyPart body1 = new MimeBodyPart(); //附件1
            body1.setDataHandler(new DataHandler(new FileDataSource(path)));

            body1.setFileName(MimeUtility.encodeText(fileName));

            MimeMultipart mm = new MimeMultipart();
            mm.addBodyPart(mimeBodyPart);
            mm.addBodyPart(body1);

            message.setContent(mm);
            //得到邮箱对象
            Transport transport = session.getTransport();
            //连接smtp服务器
            transport.connect(user, password);
            //发送邮件
            transport.sendMessage(message, message.getAllRecipients());
            //关闭邮件对象
            transport.close();
        } catch (Exception e) {
            logger.error("error is", e);
            return false;
        }
        return true;
    }

    private  InternetAddress[] buildArray(String emails) throws AddressException {
        String[] emailArr = emails.trim().split(";");
        InternetAddress[] internetAddresses = new InternetAddress[emailArr.length];
        for (int i = 0; i < emailArr.length; i++) {
            internetAddresses[i] = new InternetAddress(emailArr[i]);
        }

        return internetAddresses;
    }
}

生成excel工具类

package com.chinasoft.hilink.util;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;

import java.io.*;
import java.util.List;
import java.util.Map;

/**
 * 生成Excel文件的工具类
 */
public class exportUtils {

    /**
     * 创建excel文档,
     * @param list 数据
     * @param keys list中map的key数组集合
     * @param columnNames excel的列名
     * */
    public static Workbook createWorkBook(List<Map<String, Object>> list,String []keys,String columnNames[],String fileName) {
        // 创建excel工作簿
        //SXSSFWorkbook wb = new SXSSFWorkbook(100);//在内存中只保留100行记录,超过100就将之前的存储到磁盘里\
        HSSFWorkbook wb = new HSSFWorkbook();
        // 创建第一个sheet(页),并命名
        Sheet sheet = wb.createSheet(fileName);
        // 手动设置列宽。第一个参数表示要为第几列设;,第二个参数表示列的宽度,n为列高的像素数。
        for(int i=0;i<keys.length;i++){
            sheet.setColumnWidth(i, (int) (35.7 * 150));
        }

        // 创建两种单元格格式
        CellStyle cs = wb.createCellStyle();
        CellStyle cs2 = wb.createCellStyle();

        // 创建两种字体
        Font f = wb.createFont();
        Font f2 = wb.createFont();

        // 创建第一种字体样式(用于列名)
        f.setFontHeightInPoints((short)10);
        f.setColor(IndexedColors.BLACK.getIndex());

        // 创建第二种字体样式(用于值)
        f2.setFontHeightInPoints((short)10);
        f2.setColor(IndexedColors.BLACK.getIndex());

        // 设置第一种单元格的样式(用于列名)
        cs.setFont(f);
        cs.setVerticalAlignment(VerticalAlignment.CENTER);//垂直居中
        // 设置第二种单元格的样式(用于值)
        cs2.setFont(f2);
        // 创建第一行
        Row row = sheet.createRow(0);
        //设置列名
        Cell cellHead = null;
        for(int i=0;i<columnNames.length;i++){
            cellHead = row.createCell(i);
            cellHead.setCellValue(columnNames[i]);
            cellHead.setCellStyle(cs);
        }
        //设置每行每列的值
        for (int i = 0; i < list.size(); i++) {
            // Row 行,Cell 方格 , Row 和 Cell 都是从0开始计数的
            // 创建一行,在页sheet上
            Row row1 = sheet.createRow(i+1);
            // 在row行上创建一个方格
            for(int j=0;j<keys.length;j++){
                Cell cell = row1.createCell(j);
                //System.err.println("list.get(i).get(keys[j]).toString()="+list.get(i).get(keys[j]).toString());
                cell.setCellValue(list.get(i).get(keys[j]) == null?" ": list.get(i).get(keys[j]).toString());
                cell.setCellStyle(cs2);
            }
        }
        return wb;
    }

    public static Workbook createWorkBookByWorkbook(List<Map<String, Object>> list,String []keys,String columnNames[],String fileName,Workbook wb) {
        // 创建excel工作簿
        //SXSSFWorkbook wb = new SXSSFWorkbook(100);//在内存中只保留100行记录,超过100就将之前的存储到磁盘里\
        // 创建第一个sheet(页),并命名
        Sheet sheet = wb.createSheet(fileName);
        // 手动设置列宽。第一个参数表示要为第几列设;,第二个参数表示列的宽度,n为列高的像素数。
        for(int i=0;i<keys.length;i++){
            sheet.setColumnWidth(i, (int) (35.7 * 150));
        }

        // 创建两种单元格格式
        CellStyle cs = wb.createCellStyle();
        CellStyle cs2 = wb.createCellStyle();

        // 创建两种字体
        Font f = wb.createFont();
        Font f2 = wb.createFont();

        // 创建第一种字体样式(用于列名)
        f.setFontHeightInPoints((short)10);
        f.setColor(IndexedColors.BLACK.getIndex());

        // 创建第二种字体样式(用于值)
        f2.setFontHeightInPoints((short)10);
        f2.setColor(IndexedColors.BLACK.getIndex());

        // 设置第一种单元格的样式(用于列名)
        cs.setFont(f);
        cs.setVerticalAlignment(VerticalAlignment.CENTER);//垂直居中
        // 设置第二种单元格的样式(用于值)
        cs2.setFont(f2);
        // 创建第一行
        Row row = sheet.createRow(0);
        //设置列名
        Cell cellHead = null;
        for(int i=0;i<columnNames.length;i++){
            cellHead = row.createCell(i);
            cellHead.setCellValue(columnNames[i]);
            cellHead.setCellStyle(cs);
        }
        //设置每行每列的值
        for (int i = 0; i < list.size(); i++) {
            // Row 行,Cell 方格 , Row 和 Cell 都是从0开始计数的
            // 创建一行,在页sheet上
            Row row1 = sheet.createRow(i+1);
            // 在row行上创建一个方格
            for(int j=0;j<keys.length;j++){
                Cell cell = row1.createCell(j);
                //System.err.println("list.get(i).get(keys[j]).toString()="+list.get(i).get(keys[j]).toString());
                cell.setCellValue(list.get(i).get(keys[j]) == null?" ": list.get(i).get(keys[j]).toString());
                cell.setCellStyle(cs2);
            }
        }
        return wb;
    }
}