标签:
/* 工具类 2016年8月5日16:47:04 */ var db = {}; var mysql = require('mysql'); var nodemailer = require('nodemailer'); var pool = mysql.createPool({ connectionLimit : 10, host : 'localhost', user : 'root', password : '123456', database : 'nodejs' }); //执行sql语句并返回结果 db.query = function(sql, callback){ if (!sql) { callback(); return; } pool.query(sql, function(err, rows, fields) { if (err) { console.log(err); callback(err, null); return; }; callback(null, rows, fields); }); }; //发送邮件,带附件 db.sendMail = function (xlsxname, callback) { var transporter = nodemailer.createTransport({ service: 'qq', auth: { user: '452076103@qq.com', pass: 'drckgvaniifuxxxx' } }); var mailOptions = { from: '452076103@qq.com', //你的邮箱 to: `527828938@qq.com`, //你老板的邮箱 subject: '老板,您要的excel来了,格式您自己处理下!', html: `<h2>我发誓,我是手动导出的</h2>` , attachments:[{ filename : xlsxname, path : `./${xlsxname}` }] }; transporter.sendMail(mailOptions, function (error, info) { if (error) { callback(error,null); }else{ callback(null,info); } }); } //格式化当前时间 db.nowDate = function(){ var date = new Date(); var fmtTwo = function (number) { return (number < 10 ? '0' : '') + number; } var yyyy = date.getFullYear(); var MM = fmtTwo(date.getMonth() + 1); var dd = fmtTwo(date.getDate()); var HH = fmtTwo(date.getHours()); var mm = fmtTwo(date.getMinutes()); var ss = fmtTwo(date.getSeconds()); return '' + yyyy + '-' + MM + '-' + dd + ' ' + HH + ':' + mm + ':' + ss; } module.exports = db;
var async = require('async'); var xlsx = require('node-xlsx'); var schedule = require("node-schedule"); var mysql = require('./mysql'); var fs = require('fs'); var auto = function(){ //查询数据,并转化成生成xlsx所需的格式 var task1 = function(callback){ mysql.query('select * from Users',function(err, rows, fields){ if (err) { callback(err,null); return; } var datas = []; rows.forEach(function(row){ var newRow = []; for(var key in row){ newRow.push(row[key]); } datas.push(newRow); }) callback(null, datas); }) } //生成xlsx文件 var task2 = function(datas, callback){ var buffer = xlsx.build([{name: "今天的收入", data: datas}]); var xlsxname = `${mysql.nowDate().split(' ')[0]}.xlsx`; fs.writeFile(xlsxname, buffer, 'binary',function(err){ if (err) { callback(err,null); return; } callback(null, xlsxname); }) } //发送邮件,返回信息 var task3 = function(xlsxname, callback){ mysql.sendMail(xlsxname, function(err, info){ if (err) { callback(err, null); return; } callback(null, info); }) } async.waterfall([task1, task2 ,task3], function(err, result){ if (err) { console.log(err); return; } console.log(result); }) } var rule = new schedule.RecurrenceRule(); var times = [1,6,11,16,21,26,31,36,41,46,51,56]; rule.second = times; schedule.scheduleJob(rule, function(){ auto(); });
nodejs实现,每天定时自动读取数据库数据-生成excel表格-发送给老板邮箱
标签:
原文地址:http://blog.csdn.net/zzwwjjdj1/article/details/52129192