美文网首页
基于POI和JavaMail实现读取Excel表格内容一键群发邮

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

作者: 天谴残魂 | 来源:发表于2018-05-07 00:05 被阅读321次

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


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

    <div class="panel-title">
            <div>excel上传:</div>
    </div>
    <form action="${pageContext.request.contextPath }/employee/excelpath.action"
       role="form" enctype="multipart/form-data" method="post" onsubmit="return submitTest()">
                    <div class="panel-title">
                              <div align="left">
                              <input type="file" id="file" name="file" >
                              </div>            
                    </div>
                    <div class="panel-title">
                      <input type="submit" value="发送邮件" class="btn btn-success btn-sm">
                    </div>
        </form>
    <script src="${pageContext.request.contextPath }/js/jquery-1.9.1.js"></script>
    <script type="text/javascript">
        /*导入员工工资表格*/          
        function submitTest(){
            var fileName = $("#file").val();  
             if(fileName.length > 1 && fileName ) {    
                 var ldot = fileName.lastIndexOf(".");  
                 var type = fileName.substring(ldot + 1).toLowerCase();  
                 if(type == "xls" || type == "xlsx") { 
                     return true;
                   }
                 else{
                     alert("文件格式不正确,请重新选择!");
                     $("#file").val(""); 
                     return false;
                     
                     
                 }
              }else{
                  alert("请选择你要发送邮箱的exce表格文件!");
                  return false;
              }
        }
        </script>
    

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

    <!-- excel表格 -->
    <!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi</artifactId>
        <version>3.8</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml</artifactId>
        <version>3.8</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml-schemas -->
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml-schemas</artifactId>
        <version>3.8</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-scratchpad -->
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-scratchpad</artifactId>
        <version>3.8</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.apache.xmlbeans/xmlbeans -->
    <dependency>
        <groupId>org.apache.xmlbeans</groupId>
        <artifactId>xmlbeans</artifactId>
        <version>2.3.0</version>
        <!-- 邮箱 -->
    </dependency>  
            <dependency> 
            <groupId>javax.mail</groupId>
            <artifactId>mail</artifactId>
            <version>1.4.5</version>
        </dependency>
    

    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<String[]> list = new ArrayList<String[]>();  
            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++){ //为了过滤到第一行因为我的第一行是数据库的列</span>  
                        //获得当前行  
                        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]+"你好:<br><pre>   以下是你"+list.get(i)[2]+"份的工资条,"+list.get(i)[3]+"<br>  如有疑问请找前台统计好,前台上交财务部统一处理。谢谢合作!</pre>");
                }
             
            }  
            //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的授权码
    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","xxxxxxxxx@qq.com");
    
            //第一步:创建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("xxxxxxxxxx@qq.com", "你的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+"'<xxxxxxxxx@qq.com>'"));
                //第五步:设置接收人信息
                ts.sendMessage(message, InternetAddress.parse(to));
    
            } catch (Exception ex) {
                // TODO Auto-generated catch block
                ex.printStackTrace();
            }
    
            return false;
    
        }
    }
    
    6.成功的截图

    相关文章

      网友评论

          本文标题:基于POI和JavaMail实现读取Excel表格内容一键群发邮

          本文链接:https://www.haomeiwen.com/subject/xtsprftx.html