月报项目(定时查询数据库获取数据插入指定excel并邮件发送Demo)

本项目处理查询数据库并将数据输出到指定excel,然后以邮件形式发送的demo。

1,datas.properties文件:

url_north=jdbc:sqlserver://Chncitosql02:1433;integratedSecurity=true;DatabaseName=SISCN
url_sourth=jdbc:sqlserver://Chncitosql05:2433;integratedSecurity=true;DatabaseName=SISCN
sheetName=Details
componyTitle=AIA China eBusiness Statistic Report
fromFile=D:\\AIA_SIS\\AIA China eAgent system Statistic Report 201710.xls
toFile=D:\\AIA_SIS\\AIA China eAgent system Statistic Report 201710.xls
[email protected]
[email protected]

2,连接数据库(使用自己用的数据库)

package com.cn.importExcel;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
public class ConnectionData {
    //生产
    static String url_north=SISUtil.getDatas().getUrl_north();
    static String url_sourth=SISUtil.getDatas().getUrl_sourth();
    //uat
//    static String url_north="jdbc:sqlserver://chot3r8csql11:1433;DatabaseName=choa1sis";
//    static String userName="devplogin";
//    static String password="g47V58Cv";
//    static String url_sourth="jdbc:sqlserver://chot3r8csql11:1433;DatabaseName=choa1sis";
    @SuppressWarnings("null")
    public static Map<String,Object> getData(String url){
        Connection connection=null;
        PreparedStatement pStatement=null;
        ResultSet rSet=null;
        String[] sqls=getSqls(url);
        Map<String,Object> maps=new HashMap<String,Object>();
        connection=getConnection(url);
        try {    
            for(int i=0;i<=4;i++){
                Map<Object,Object> map=new HashMap<Object,Object>();
                rSet=getResultSet(sqls[i],connection,pStatement,rSet);
                while(rSet.next()){
                    switch(i){//生产
                      case 0:
                          map.put(rSet.getString("orgid"), rSet.getString("count"));
                          break;
                      case 1:
                          map.put(rSet.getString("lco"),rSet.getString("count"));
                          break;
                      case 2:
                          map.put(rSet.getString("agtco"),rSet.getString("count"));
                          break;
                      case 3:
                          map.put(rSet.getString("branch_code"), rSet.getString("sh"));
                          break;
                      case 4:
                          map.put(rSet.getString("branch_code"),rSet.getString("CheckNumber_SH"));
                          break;
                    }
                    //uat测试
//                    map.put(rSet.getString("agtco"), rSet.getString("counter"));
                }                
                //重新组装数据顺序
                if(i==1 || i==2){
                    maps.put("map"+i, map);
                    maps.put("map"+(i+4), map);//1==5,2==6
                }else if(i==3 || i==4){
                    maps.put("map"+i, getSpecialData());
                    maps.put("map"+(i+4), map);
                }else{                    
                    maps.put("map"+i, map);
                }
                
            }            
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if(connection !=null){
                    connection.close();
                }
                if(pStatement !=null){
                    pStatement.close();
                }
                if(rSet !=null){
                    rSet.close();
                }                
            } catch (SQLException e) {
                e.printStackTrace();
            }            
        }
        return maps;
    }
    public static Map<Object,Object> getSpecialData(){
        Map<Object,Object> map=new HashMap<Object,Object>();
        map.put("0986", "0");
        map.put("1186", "0");
        map.put("1286", "0");
        map.put("1086", "0");
        map.put("2586", "0");
        map.put("2686", "0");
        map.put("2786", "0");
        map.put("2886", "0");
        return map;
    }
    public static ResultSet getResultSet(String sql,Connection connection,PreparedStatement pStatement,ResultSet rSet) throws Exception{
        pStatement=connection.prepareStatement(sql);
        rSet=pStatement.executeQuery();
        return rSet;
    }
    public static Connection getConnection(String url){
        Connection connection=null;
        try {
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
            connection=DriverManager.getConnection(url);//生产
//            connection=DriverManager.getConnection(url,userName,password);//uat测试
        } catch (Exception e) {
            e.printStackTrace();
        }         
        return connection;
    }
    public static String[] getSqls(String url){
        //生产
        String sql00="SELECT orgid, count(distinct userid+orgid) as count FROM SHPOSAUTO.dbo.logondata where SYSTEMNAME='SIS' and logontime <= CONVERT(datetime,convert(varchar(10),dateadd(d,-1,dateadd(m,-1,DATEADD(mm, DATEDIFF(m,0,getdate())+1, 0))),112)) and  logontime >= CONVERT(datetime, CONVERT(varchar(10),DATEADD(m,-1 ,dateadd(dd,-day(getdate())+1,getdate())) ,112)) and substring(userid,3,2) <='99' and substring(userid,3,2) >='00'group by orgid";
        String sql01="SELECT orgid, count(distinct userid+orgid) as count FROM GZPOSAUTO.dbo.logondata where SYSTEMNAME='SIS' and logontime <= CONVERT(datetime,convert(varchar(10),dateadd(d,-1,dateadd(m,-1,DATEADD(mm, DATEDIFF(m,0,getdate())+1, 0))),112)) and  logontime >= CONVERT(datetime, CONVERT(varchar(10),DATEADD(m,-1 ,dateadd(dd,-day(getdate())+1,getdate())) ,112)) and substring(userid,3,2) <='99' and substring(userid,3,2) >='00'group by orgid;";        
        String sql1="select lco,lyear,lmonth,sum(lcount) count from siscn.dbo.sisdlog where lyear = Year(getDate()) and lmonth=convert(char(2),MONTH(GETDATE())-1) and substring(lfunc,2,1) in ('1','2')  and  substring(lfunc,1,1)=0 group by lco,lyear,lmonth,substring(lfunc,1,1);";
        String sql2="select agtco,count(1) as count from siscn.dbo.proposal where appdate between convert(datetime,convert(varchar(10),dateadd(mm,-1,dateadd(dd,-day(GETDATE())+1,GETDATE())),23)+' 00:00:00.000') and convert(datetime,convert(varchar(10),dateadd(dd,-day(GETDATE()),GETDATE()),23)+' 23:59:59.000') group by agtco;";        
        String sql3="SELECT branch_code,count(*) as sh FROM AMCMS..meeting WHERE 1=1 AND (YEAR(start_time) = Year(getDate())) AND (MONTH(start_time) = (month(getdate())-1)) group by branch_code;";
        String sql4="SELECT (SUM(CASE WHEN A.arrive_check = '1' THEN 1 ELSE 0 END)+SUM(CASE WHEN A.arrive_check = '2' THEN 1 ELSE 0 END)+ SUM(CASE WHEN A.arrive_check = '6' THEN 1 ELSE 0 END)) AS 'CheckNumber_SH',b.branch_code FROM AMCMS..meeting_agent A INNER JOIN AMCMS..meeting B ON A.meeting_id = B.meeting_id WHERE 1=1 and (YEAR(B.start_time) = Year(getDate()) AND (MONTH(B.start_time) = (month(getdate())-1))) group by b.branch_code;";
        String[] sqls1=new String[]{((url!=null && url.contains("Chncitosql02:1433"))?sql00:sql01),sql1,sql2,sql3,sql4};
        //uat 测试
//        String sql="select agtco,count(issname) as counter from proposal where agtco in('0986','1186','1286','1086','2586','2686','2786','2886') group by agtco union select 'total' as agtco, count(issname) as counter from proposal where agtco in('0986','1186','1286','1086','2586','2686','2786','2886');";
//        String[] sqls1=new String[]{sql,sql,sql,sql,sql};
        return sqls1;
    }
    public static void main(String[] args) {
        Map<String,Object> maps_north=getData(url_north);
        Map<Object,Object> map=new HashMap<Object,Object>();
        for(int i=0;i<maps_north.size();i++){
            @SuppressWarnings("unchecked")
            Map<Object,Object> value=(Map<Object,Object>)maps_north.get("map"+i);
            System.out.println("---------");            
        }
        Map<String,Object> maps_sourth=getData(url_sourth);
        System.out.println("------------");
    }
}
3,操作指定excel(导入导出数据至指定数据库)

package com.cn.importExcel;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.util.CellRangeAddress;
/**
 * 友邦SIS周报2017   November   AIA
 * @author Administrator
 *
 */
public class ImportAndUpdate {
    public static boolean isUpdate=false;//是否已经更新过
    private static String sheetName=SISUtil.getDatas().getSheetName();
    private static String componyTitle=SISUtil.getDatas().getComponyTitle();
    static String fromFile=SISUtil.getDatas().getFromFile();
    private static String toFile=SISUtil.getDatas().getToFile();
//    static String fromFile="C:\\Users\\nsnp674\\Desktop\\AIA China eAgent system Statistic Report 201710.xls";
//    private static String toFile="C:\\Users\\nsnp674\\Desktop\\AIA China eAgent system Statistic Report 201710.xls";
    static int count=0;//用来统计执行importExcel的次数
    //需要填写的地方
    private static final String[] points=new String[]{"Sales illustration System","# UNIQUE agent accesses/month",
            "SIS","Number of agents access per month","Number of proposal generated per month",
            "eSIS New Solution","Number of agents access per month","Number of proposal generated per month",
            "SIS+eSIS","Number of agents access per month","Number of proposal generated per month",
            "Agent Morning Call Management System","Number of meeting registered per month ","Count of check in per month"};
    public static void importExcel(Map<String,Object> dataMaps) throws Exception{
        InputStream is;
        OutputStream os;
        HSSFWorkbook fromWork;
        count++;
        try {
            is = new FileInputStream(new File(fromFile));
            fromWork = new HSSFWorkbook(is);
            is.close();// 对同一个文件进行操作时需要及时将用完的输入流关闭,否则输出流在引用这个文件时会报错
            os = new FileOutputStream(new File(toFile));
            HSSFSheet fromSheet = getSheetName(fromWork);            
            List<Object[]> lists=getRowAndColAndValues(fromWork,fromSheet,dataMaps,count);
            System.out.println("最后匹配完得到的结果数量为:"+lists.size());
            insert(fromSheet, lists);//循环插入值
            fromWork.write(os);
            os.flush();
            isUpdate=true;
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }              
    }
    //获取指定sheetName
    public static HSSFSheet getSheetName(HSSFWorkbook fromWork){
        HSSFSheet fromSheet = fromWork.getSheetAt(1);// 获取第一个sheet
        int sheets = fromWork.getNumberOfSheets();
        for(int i=0;i<sheets;i++){
            String sheet=fromWork.getSheetName(i);
            if(sheetName.equals(sheet)){
                fromSheet=fromWork.getSheetAt(i);
            }            
        }    
        return fromSheet;
    }  
    public static Object getValue(HSSFCell hCell) {//处理excel值的格式并返回
        if (hCell != null) {
            if (hCell.getCellType() == HSSFCell.CELL_TYPE_BLANK) {
                // System.out.println("");
                return "";
            } else if (hCell.getCellType() == HSSFCell.CELL_TYPE_BOOLEAN) {
                // System.out.println(hCell.getBooleanCellValue());
                return hCell.getBooleanCellValue();
            } else if (hCell.getCellType() == HSSFCell.CELL_TYPE_FORMULA) {
                // System.out.println(hCell.getCellFormula());
                return hCell.getCellFormula();
            } else if (hCell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
                // System.out.println(hCell.getNumericCellValue());
                return hCell.getNumericCellValue();
            } else if (hCell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
                // System.out.println(hCell.getStringCellValue());
                return hCell.getStringCellValue();
            }
        }
        return null;
    }
    public static int[] getMergedRegion(HSSFSheet sheet, int row, int column) {// 判断指定坐标是否是合并单元格并返回
        int[] list = null;
        int sheetMergeCount = sheet.getNumMergedRegions();
        for (int i = 0; i < sheetMergeCount; i++) {
            CellRangeAddress range = sheet.getMergedRegion(i);
            int firstColumn = range.getFirstColumn();
            int lastColumn = range.getLastColumn();
            int firstRow = range.getFirstRow();
            int lastRow = range.getLastRow();
            if (row >= firstRow && row <= lastRow) {
                if (column >= firstColumn && column <= lastColumn) {
                    list = new int[] { firstColumn, lastColumn, firstRow, lastRow };
                    // System.out.println("行的区间:"+firstRow+"~"+lastRow+";列的区间:"+firstColumn+"~"+lastColumn);
                }
            }
        }
        return list;
    }
    // 获取月份所在列
    public static int getMonthCell(HSSFSheet fromSheet) {
        int firstRow = fromSheet.getFirstRowNum();
        int lastRow = fromSheet.getLastRowNum();
        int rows = lastRow - firstRow;// 获取总行数,下标从0开始
        int[] yearBetweens = null;
        int monthCell = 0;
        for (int i = 0; i <= rows; i++) {
            if (rows == 0)
                break;
            HSSFRow hRow = fromSheet.getRow(i);
            if (hRow == null)
                continue;
            int perColumns = hRow.getPhysicalNumberOfCells();
            int count = 0;
            int columns = 0;
            while (count < perColumns) {
                HSSFCell hCell = hRow.getCell(columns);
                int[] mergedRegion = getMergedRegion(fromSheet, i, columns);
                Object obj = getValue(hCell);
                if ((obj != null) || mergedRegion != null) {
                    count++;
                    if (obj.equals(getBefDate()[0]) && mergedRegion != null) {// 定位年份标题但不会返回
                        yearBetweens = mergedRegion;
//                        System.out.println("当年标题合并单元格行的区间:" + mergedRegion[2] + "~" + mergedRegion[3] + ";列的区间:"
//                                + mergedRegion[0] + "~" + mergedRegion[1]);
                    } else if (obj.equals(getBefDate()[1]) && columns >= yearBetweens[0] && columns <= columns) {// 定位月份
                        monthCell = columns;
                    }
                }
                columns++;
            }
        }
        return monthCell;
    }
    // 获取各标题所在行
    public static List<int[]> getPerPointRows(HSSFWorkbook fromWork,HSSFSheet fromSheet) {
        int firstRow = fromSheet.getFirstRowNum();
        int lastRow = fromSheet.getLastRowNum();
        int rows = lastRow - firstRow;// 获取总行数,下标从0开始    
        List<int[]> list=new ArrayList<int[]>();
        int[] onePointCell = null;
        int[] twoPointCell = null;
        int[] threePointCell=null;
        for (int i = 0; i <= rows; i++) {
            if (rows == 0)
                break;
            HSSFRow hRow = fromSheet.getRow(i);
            if (hRow == null)
                continue;
            int perColumns = hRow.getPhysicalNumberOfCells();
            int count = 0;
            int columns = 0;
            while (count < perColumns) {
                HSSFCell hCell = hRow.getCell(columns);
                int[] mergedRegion = getMergedRegion(fromSheet, i, columns);
                Object obj = getValue(hCell);
                if ((obj != null) || mergedRegion != null) {
                    count++;
                    int fontColor = fromWork.getFontAt(hCell.getCellStyle().getFontIndex()).getColor();// 获取字体颜色用于区分是第一层级标题还是第二层级标题
                    for (int j = 0; j < points.length; j++) {                        
                        if (obj.equals(points[j]) && fontColor == 32767) {// 黑色:一级,蓝色:二级
                            if(threePointCell!=null){
                                if(i<=threePointCell[0] || columns>=threePointCell[1]){
                                    continue;
                                }
                            }else if(twoPointCell!=null){
                                if(i<=twoPointCell[0] || columns>=twoPointCell[1]){
                                    continue;
                                }
                            }else if(j>0){
                                continue;
                            }
                            onePointCell = new int[] { i, columns };
                        } else if (obj.equals(points[j]) && fontColor == 12) {
                            if (onePointCell != null && i == onePointCell[0] + 1 && columns == onePointCell[1] + 1) {
                                twoPointCell = new int[]{ i, columns };
                                onePointCell=null;
                                list.add(twoPointCell);
                            } else if (twoPointCell != null && i == twoPointCell[0] + 10 && columns == twoPointCell[1]) {
                                threePointCell=new int[]{ i, columns};
                                twoPointCell=null;
                                list.add(threePointCell);
                            }
                        }
                    }
                }
                columns++;
            }
        }
        return list;
    }
    //将所得到的行列重新组装
    public static List<Integer[]> getFinalCell(HSSFWorkbook fromWork,HSSFSheet fromSheet){
        int monthColumn = 0;
        if (getMonthCell(fromSheet) > 0) {
            monthColumn = getMonthCell(fromSheet);
        }
//        System.out.println("上月月份所在列为:" + monthColumn);
        //获取每个条件下所在行数集合
        List<int[]> list=getPerPointRows(fromWork, fromSheet);
        //重新组合得到条件所在的行以及月份所在的列
        List<Integer[]> finalCells=new ArrayList<Integer[]>();
        for(int[] i:list){
//            System.out.println("每个条件对应的行数为:"+i[0]+",列数为:"+i[1]+",月份所在的列数为:"+monthColumn);
            finalCells.add(new Integer[]{i[0],i[1],monthColumn});
        }
        return finalCells;
    }    
    //将数据库数据与组装后的excel数据进行匹配得到最后需要填充的行、列、值
    @SuppressWarnings("unchecked")
    public static List<Object[]> getRowAndColAndValues(HSSFWorkbook fromWork,HSSFSheet fromSheet,Map<String,Object> dataMaps,int count){
        List<Integer[]> finalCells=getFinalCell(fromWork, fromSheet);
//        Map<String,Object> dataMaps=getSqlserverDatas();
        List<Object[]> lists=new ArrayList<Object[]>();
        for(int i=0;i<finalCells.size();i++){
            Map<Object,Object> mapIn=(Map<Object,Object>)dataMaps.get("map"+i);    
            int total=0;//用来记录各渠道数据
            for(int j=0;j<9;j++){
                int row=finalCells.get(i)[0]+j+1;//行数累加获取,列数不变
                int column=finalCells.get(i)[1];
                String city=fromSheet.getRow(row).getCell(column).getStringCellValue();                
                for(Map.Entry<Object,Object> entry:mapIn.entrySet()){                                                                        
                    String key=(String)entry.getKey();
                    String value=(String)entry.getValue();
                    if(("SH".equals(city) && ("N00001".equals(key)||"0986".equals(key)))
                            ||("BJ".equals(city) && ("N00002".equals(key)||"1186".equals(key)))
                            ||("JS".equals(city) && ("N00003".equals(key)||"1286".equals(key)))
                            ||("GD".equals(city) && ("S00001".equals(key)||"2586".equals(key)))
                            ||("SZ".equals(city) && ("S00002".equals(key)||"1086".equals(key)))
                            ||("DG".equals(city) && ("S00003".equals(key)||"2886".equals(key)))
                            ||("JM".equals(city) && ("S00004".equals(key)||"2786".equals(key)))
                            ||("FS".equals(city) && ("S00005".equals(key)||"2686".equals(key)))){    
                        total=total+Integer.parseInt(value);
                        lists.add(new Object[]{row,finalCells.get(i)[2],value});                                                
//                        System.out.println("该城市为:"+key+"需要填的行为:"+row+",列为:"+finalCells.get(i)[2]+",值为:"+value);
                        break;
                    }                                        
                }
                if(j==8 && "Total".equals(city)){//南北方数据分开需要先判断total中是否有值,有值则取值相加在放入
                    String totalValue=fromSheet.getRow(row).getCell(finalCells.get(i)[2]).getStringCellValue();
                    if(totalValue != null && !"".equals(totalValue)){
                        if(count == 1 || count > 2){//如果本来total就有值则需先清空,执行超过两次也需要先清空数据。
                            fromSheet.getRow(row).getCell(finalCells.get(i)[2]).setCellValue(0);
                            totalValue="0";
                        }
                        total=Integer.parseInt(totalValue)+total;                        
//                        System.out.println("total累加之后值为:"+totalValue);
                    }
                    lists.add(new Object[]{row,finalCells.get(i)[2],String.valueOf(total)});
                }
            }            
        }
        return lists;
    }  
    // 向指定的单元格内加入值 如果该单元格为null,先创建在填值
    public static void insert(HSSFSheet fromSheet,List<Object[]> lists) {
        for(int i=0;i<lists.size();i++){
            int row=(Integer)lists.get(i)[0];
            int column=(Integer)lists.get(i)[1];
            Object obj=lists.get(i)[2];
            HSSFRow hRow = fromSheet.getRow(row);
            if (hRow == null) {
                hRow = fromSheet.createRow(row);
            }
            HSSFCell hCell = hRow.getCell(column);
            if (hCell == null) {
                hCell = hRow.createCell(column);
            }
            hCell.setCellValue(String.valueOf(obj));
        }        
    }
//excel里面大标题动态获取    组装:company+年
    public static String[] getBefDate() {
        String[] months = new String[] { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov",
                "Dec" };
        Calendar c = new GregorianCalendar();
        String befDate = c.get(Calendar.YEAR) + "," + months[c.get(Calendar.MONTH) - 1];
        String[] yearAndMonth = befDate.split(",");
        yearAndMonth[0] = componyTitle + yearAndMonth[0];
        return yearAndMonth;
    }
    public static Map<String,Object> getSqlserverDatas_North(){//模拟数据库数据
        Map<Object,Object> mapIn=new HashMap<Object,Object>();
        Map<String,Object> mapOut=new HashMap<String,Object>();
        for(int i=0;i<4;i++){
            mapIn.put("N00001", "1234");
            mapIn.put("N00002", "1234");
            mapIn.put("N00003", "1234");
            mapOut.put("map"+i, mapIn);
            mapIn=new HashMap<Object,Object>();
        }
        for(int i=4;i<9;i++){
            mapIn.put("0986", "6541");
            mapIn.put("1186", "6541");
            mapIn.put("1286", "6541");
            mapOut.put("map"+i, mapIn);
            mapIn=new HashMap<Object,Object>();
        }                
        return mapOut;
    }
    public static Map<String,Object> getSqlserverDatas_Sourth(){//模拟数据库数据
        Map<Object,Object> mapIn=new HashMap<Object,Object>();
        Map<String,Object> mapOut=new HashMap<String,Object>();
        for(int i=0;i<4;i++){
            mapIn.put("S00001", "1234");
            mapIn.put("S00002", "1234");
            mapIn.put("S00003", "1234");
            mapIn.put("S00004", "1234");
            mapIn.put("S00005", "1234");
            mapOut.put("map"+i, mapIn);
            mapIn=new HashMap<Object,Object>();
        }
        for(int i=4;i<9;i++){
            mapIn.put("1086", "6541");
            mapIn.put("2586", "6541");
            mapIn.put("2686", "6541");
            mapIn.put("2786", "6541");
            mapIn.put("2886", "6541");
            mapOut.put("map"+i, mapIn);
            mapIn=new HashMap<Object,Object>();
        }                
        return mapOut;
    }
    //测试
    public static void main(String[] args) {
        try {
            importExcel(getSqlserverDatas_North());
            importExcel(getSqlserverDatas_Sourth());
            if(isUpdate)
                System.out.println("恭喜已经完成填写!");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
4,发送邮件

package com.cn.importExcel;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
public class SendEmail {
    static boolean isSendSuccess=false;
    public static Session getSession() throws Exception {
        Properties props = new Properties();
        props.setProperty("mail.host", "smtphk-int.aia.biz");
        props.setProperty("mail.transport.protocol", "smtp");
        Session mail_session = Session.getInstance(props);
        return mail_session;
    }
public static void sendEmail(String path) throws Exception{
        String sender = "[email protected]";
        //实际发送
        String[] receivers =SISUtil.getDatas().getReceivers();
        String[] ccs =SISUtil.getDatas().getCcs();     
        //测试
//        String[] receivers ={"[email protected]"};
//        String[] ccs ={"[email protected]"};
        Session mailSession = getSession();
        InternetAddress Sender = new InternetAddress(sender);
        List<InternetAddress> recipinets = new ArrayList<InternetAddress>();
        for (String receiverItem : receivers) {
            if (!"".equals(receiverItem)) {
                recipinets.add(new InternetAddress(receiverItem));
            }
        }
        Message msg = new MimeMessage(mailSession);
        msg.setFrom(Sender);
        msg.addRecipients(Message.RecipientType.TO, recipinets.toArray(new InternetAddress[0]));
        if (ccs != null && ccs.length > 0) {
            List<InternetAddress> ccAddresses = new ArrayList<InternetAddress>();
            for (String ccItem : ccs) {
                if (!"".equals(ccItem)) {
                    ccAddresses.add(new InternetAddress(ccItem));
                }
            }
            if (!ccAddresses.isEmpty()) {
                msg.addRecipients(Message.RecipientType.CC, ccAddresses.toArray(new InternetAddress[0]));
            }
        }
        msg.setSentDate(new java.util.Date());
        msg.setSubject("SIS Monthly Data!");
        Multipart mp = new MimeMultipart();
        MimeBodyPart mbp = new MimeBodyPart();
        mbp.setContent("<html><head></head><body>附件是SIS Monthly Data,请查收,谢谢!(此邮件由系统自动发出,请勿回复,如有数据问题请联系[[email protected]])</body></html>",
                "text/html; charset=UTF-8");
        mp.addBodyPart(mbp);
        File file = new File(path);
        if (file!=null && file.getPath()!=null) {
            BodyPart attachmentBodyPart = new MimeBodyPart();
            FileDataSource fds = new FileDataSource(path);
            attachmentBodyPart.setDataHandler(new DataHandler(fds));
            attachmentBodyPart.setFileName(fds.getName());
            mp.addBodyPart(attachmentBodyPart);
        }
        msg.setContent(mp);
        Transport.send(msg);
        System.out.println("发送邮件成功!");
        isSendSuccess=true;
    }   
    public static void main(String[] args) {
        try {
            sendEmail("C:\\Users\\nsnp674\\Desktop\\SIS环境列表20170801.xls");
            System.out.println("OK!");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
5,获取datas.properties文件数据并封装至SISUtil中

package com.cn.importExcel;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;
//读取datas.properties数据
public class SISUtil {
    //数据库南北方url
    private String url_north;
    private String url_sourth;
    //excel相关参数
    private String sheetName;
    private String componyTitle;
    private String fromFile;
    private String toFile;
    //email中相关参数
    private String[] receivers;
    private String[] ccs;
    public static SISUtil getDatas(){
        SISUtil sisUtil=new SISUtil();
        ResourceBundle resourceBundle=PropertyResourceBundle.getBundle("datas");
        sisUtil.setUrl_north(resourceBundle.getString("url_north"));
        sisUtil.setUrl_sourth(resourceBundle.getString("url_sourth"));
        sisUtil.setSheetName(resourceBundle.getString("sheetName"));
        sisUtil.setComponyTitle(resourceBundle.getString("componyTitle"));
        sisUtil.setFromFile(resourceBundle.getString("fromFile"));
        sisUtil.setToFile(resourceBundle.getString("toFile"));
        sisUtil.setReceivers(resourceBundle.getString("receivers").split(","));
        sisUtil.setUrl_north(resourceBundle.getString("ccs"));
        return sisUtil;
    }
    public String getUrl_north() {
        return url_north;
    }
    public void setUrl_north(String url_north) {
        this.url_north = url_north;
    }
    public String getUrl_sourth() {
        return url_sourth;
    }
    public void setUrl_sourth(String url_sourth) {
        this.url_sourth = url_sourth;
    }
    public String getSheetName() {
        return sheetName;
    }
    public void setSheetName(String sheetName) {
        this.sheetName = sheetName;
    }
    public String getComponyTitle() {
        return componyTitle;
    }
    public void setComponyTitle(String componyTitle) {
        this.componyTitle = componyTitle;
    }
    public String getFromFile() {
        return fromFile;
    }
    public void setFromFile(String fromFile) {
        this.fromFile = fromFile;
    }
    public String getToFile() {
        return toFile;
    }
    public void setToFile(String toFile) {
        this.toFile = toFile;
    }
    public String[] getReceivers() {
        return receivers;
    }
    public void setReceivers(String[] receivers) {
        this.receivers = receivers;
    }
    public String[] getCcs() {
        return ccs;
    }
    public void setCcs(String[] ccs) {
        this.ccs = ccs;
    }
    public static void main(String[] args) {
        System.out.println(SISUtil.getDatas().getToFile());
    }
}
6,手动执行任务

package com.cn.importExcel;
import java.util.Map;
public class BeginRunAll {
    public static void beginRun(){
        //测试连接数据库并自动填写Excel输出到桌面
                Map<String,Object> maps_north=ConnectionData.getData(ConnectionData.url_north);
                Map<String,Object> maps_sourth=ConnectionData.getData(ConnectionData.url_sourth);
                if(maps_north!=null && maps_sourth!=null && maps_north.size()>0 && maps_sourth.size()>0){
                    try {
                        ImportAndUpdate.importExcel(maps_north);
                        if(ImportAndUpdate.isUpdate)
                            ImportAndUpdate.importExcel(maps_sourth);
                        else ImportAndUpdate.isUpdate=false;
                        if(ImportAndUpdate.isUpdate){
                            System.out.println("数据已成功导入Excel!");
                            //开始发送邮件
                            SendEmail.sendEmail(ImportAndUpdate.fromFile);
                            if(SendEmail.isSendSuccess)
                                System.out.println("邮件已发送,请知悉!");
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
    }
    public static void main(String[] args) {
        //手工执行,如果定时执行可在TimerJob中启动
        beginRun();
        if(SendEmail.isSendSuccess)
            System.out.println("所有操作已完成!");
    }    
    
}
7,定时执行任务

package com.cn.importExcel;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;
public class TimerJob{
    public static void main(String[] args) {
        System.out.println("------start-----");
        Timer timer=new Timer();
          timer.schedule(new TimerTask() {       
           @Override
           public void run() {
            System.out.println("--------run----------");
            Calendar cal=Calendar.getInstance();
            int month=cal.get(Calendar.MONTH)+1;
            int day_of_month=cal.get(Calendar.DAY_OF_MONTH);
            System.out.println("当前日期为:"+month+"月"+day_of_month+"号");
            if(day_of_month==5){
//             System.out.println("每月5号执行");
                BeginRunAll.beginRun();
                if(SendEmail.isSendSuccess)
                    System.out.println("所有操作已完成!");
            }
          }
        }, 0, 3600*24*1000);//3600*24*1000指每隔一天判断一次,如果该天是这个月的5号则执行
    }            
}

--excel文件及单独excel导入导出的源代码可参照以下地址:

http://download.csdn.net/download/qq_35255384/10152532


猜你喜欢

转载自blog.csdn.net/qq_35255384/article/details/78912038