基于POI和JavaMail实现读取Excel表格内容一键群发邮箱功能

公司财务要求做一个Excel表格工资条内容群发邮箱的功能,由于我是菜鸟项目老大就把这任务交给我来做,开始时需求没谈好做了很多白费的功夫,在这里我算是长教训!一定要谈好需求才开始做而且要找到对的人去谈需求!最终还好在各同事指点下做出来了,好了废话就不多说了下面直接上代码。
1.上传的Excel表格的内容格式


基于POI和JavaMail实现读取Excel表格内容一键群发邮箱功能_第1张图片

2.前端代码form表单multipart文件上传

excel上传:

3.java后台代码
maven需要的下的jar




    org.apache.poi
    poi
    3.8



    org.apache.poi
    poi-ooxml
    3.8



    org.apache.poi
    poi-ooxml-schemas
    3.8



    org.apache.poi
    poi-scratchpad
    3.8



    org.apache.xmlbeans
    xmlbeans
    2.3.0
    
  
         
        javax.mail
        mail
        1.4.5
    

controller层代码

package com.boyue.controller;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import javax.mail.MessagingException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.boyue.core.utils.EmailUtil;

@Controller
@RequestMapping("employee")
public class EmployeeController {
    private final static String xls = "xls";  
    private final static String xlsx = "xlsx";
    /**  
     * 读入excel文件,解析后返回  
     * @param file  
     * @throws IOException  
     * @throws MessagingException 
     */ 
   @RequestMapping(value = "excelpath")
  public String readExcel(Model model,MultipartFile file) throws IOException, MessagingException{ 
        //检查文件  
        checkFile(file);
        //System.out.println(file);
        //获得Workbook工作薄对象  
        Workbook workbook = getWorkBook(file);  
        int cellNum=0;
        //创建返回对象,把每行中的值作为一个数组,所有行作为一个集合返回  
        List list = new ArrayList();  
        if(workbook != null){  
            for(int sheetNum = 0;sheetNum < workbook.getNumberOfSheets();sheetNum++){  
                //获得当前sheet工作表  
                Sheet sheet = workbook.getSheetAt(sheetNum);  
                if(sheet == null){  
                    continue;  
                }  
                //获得当前sheet的开始行  
                int firstRowNum  = sheet.getFirstRowNum();  
                //获得当前sheet的结束行  
                int lastRowNum = sheet.getLastRowNum();  
                //循环除了第一行的所有行  
               for(int rowNum = firstRowNum+1;rowNum <= lastRowNum;rowNum++){ //为了过滤到第一行因为我的第一行是数据库的列  
                    //获得当前行  
                    Row row = sheet.getRow(rowNum);  
                    if(row == null){  
                        continue;  
                    }  
                    //获得当前行的开始列  
                    int firstCellNum = row.getFirstCellNum();  
                    //获得当前行的列数  
                    //int lastCellNum = row.getPhysicalNumberOfCells();//为空列不获取  
                   //String[] cells = new String[row.getPhysicalNumberOfCells()];  
                   int lastCellNum = row.getLastCellNum();//为空列获取  
                    String[] cells = new String[row.getLastCellNum()];
                    //循环当前行  
                    for(cellNum = firstCellNum; cellNum < lastCellNum;cellNum++){  
                        Cell cell = row.getCell(cellNum);  
                        cells[cellNum] = getCellValue(cell);  
                    }  
                    list.add(cells); 
                }  
                
            }  
            for (int i = 0; i < list.size(); i++) {
               //EmailUtil.send("收件人邮箱号","邮件标题","邮件内容")
                EmailUtil.send(list.get(i)[1],"工资情况",list.get(i)[0]+"你好:
   以下是你"+list.get(i)[2]+"份的工资条,"+list.get(i)[3]+"
如有疑问请找前台统计好,前台上交财务部统一处理。谢谢合作!
"); } } //logger.info(gson.toJson(list)); return "employee/success"; } public static void checkFile(MultipartFile file) throws IOException{ //判断文件是否存在 if(null == file){ throw new FileNotFoundException("文件不存在!"); } //获得文件名 String fileName = file.getOriginalFilename(); //判断文件是否是excel文件 if(!fileName.endsWith(xls) && !fileName.endsWith(xlsx)){ throw new IOException(fileName + "不是excel文件"); } } public static Workbook getWorkBook(MultipartFile file) { //获得文件名 String fileName = file.getOriginalFilename(); //创建Workbook工作薄对象,表示整个excel Workbook workbook = null; try { //获取excel文件的io流 InputStream is = file.getInputStream(); //根据文件后缀名不同(xls和xlsx)获得不同的Workbook实现类对象 if(fileName.endsWith(xls)){ //2003 workbook = new HSSFWorkbook(is); }else if(fileName.endsWith(xlsx)){ //2007 workbook = new XSSFWorkbook(is); } } catch (IOException e) { //logger.info(e.getMessage()); System.out.println(e.getMessage()); } return workbook; } public static String getCellValue(Cell cell){ String cellValue = ""; if(cell == null){ return cellValue; } //把数字当成String来读,避免出现1读成1.0的情况 if(cell.getCellType() == Cell.CELL_TYPE_NUMERIC){ cell.setCellType(Cell.CELL_TYPE_STRING); } //判断数据的类型 switch (cell.getCellType()){ case Cell.CELL_TYPE_NUMERIC: //数字 cellValue = String.valueOf(cell.getNumericCellValue()); break; case Cell.CELL_TYPE_STRING: //字符串 cellValue = String.valueOf(cell.getStringCellValue()); break; case Cell.CELL_TYPE_BOOLEAN: //Boolean cellValue = String.valueOf(cell.getBooleanCellValue()); break; case Cell.CELL_TYPE_FORMULA: //公式 // cellValue = String.valueOf(cell.getCellFormula()); cellValue = String.valueOf(cell.getStringCellValue()); break; case Cell.CELL_TYPE_BLANK: //空值 cellValue = ""; break; case Cell.CELL_TYPE_ERROR: //故障 cellValue = "非法字符"; break; default: cellValue = "未知类型"; break; } return cellValue; } }

4.获取发件人的IMAP授权码

在qq邮箱或者网易邮箱里开启POP3和IMAP并记录IMAP的授权码
基于POI和JavaMail实现读取Excel表格内容一键群发邮箱功能_第2张图片

5.创建邮箱发送的工具类
package com.boyue.core.utils;

import java.util.Properties;

import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import com.sun.mail.util.MailSSLSocketFactory;

public class EmailUtil {
    /**
     * 发送邮件
     * @param to       收件人邮箱
     * @param subject  标题
     * @param msg      消息内容
     * @return
     */
    public static boolean send(String to,String subject,String msg){

        Properties props = new Properties();
        
        //邮件传输的协议
        props.put("mail.transport.protocol", "smtp");
        //连接的邮件服务器
        props.put("mail.host","smtp.qq.com");
        //发送人
        props.put("mail.from","[email protected]");

        //第一步:创建session
        Session session = Session.getDefaultInstance(props);
        session.setDebug(true);

        try {
            MailSSLSocketFactory sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
            props.put("mail.smtp.ssl.enable", "true");
            props.put("mail.smtp.ssl.socketFactory", "true");
            //第二步:获取邮件传输对象
            Transport ts= session.getTransport();
            //连接邮件服务器
            ts.connect("[email protected]", "你的IMAP授权码");
            //第三步:创建邮件消息体
            MimeMessage message = new MimeMessage(session);
            //设置邮件的标题
            message.setSubject(subject, "utf-8");
            //设置邮件的内容
            message.setContent(msg,"text/html;charset=utf-8");
            //第四步:设置发送昵称
            String nick="";
            nick = javax.mail.internet.MimeUtility.encodeText("财务部");
            message.setFrom(new InternetAddress(nick+"''"));
            //第五步:设置接收人信息
            ts.sendMessage(message, InternetAddress.parse(to));

        } catch (Exception ex) {
            // TODO Auto-generated catch block
            ex.printStackTrace();
        }

        return false;

    }
}

6.成功的截图
基于POI和JavaMail实现读取Excel表格内容一键群发邮箱功能_第3张图片

你可能感兴趣的:(基于POI和JavaMail实现读取Excel表格内容一键群发邮箱功能)