一、定時導出Excel並定時發送到郵箱
首先我們先分析一下該功能有多少個小的任務點:1.Windows計划服務
2.定時導出Excel定指定路徑
3.定時發送郵件包含附件
接下來我們一個個解決,
1.1發送郵件
- 現提供一下相關資料:
http://www.cnblogs.com/ForEvErNoME/archive/2012/06/05/2529259.html
- 了解SMTP服務器
SMTP具體是指什么?
SMTP的全稱是"Simple Mail Transfer Protocol",即簡單郵件傳輸協議。它是一組用於從源地址到目的地址傳輸郵件的規范,通過它來控制郵件的中轉方式。SMTP 協議屬於 TCP/IP 協議簇,它幫助每台計算機在發送或中轉信件時找到下一個目的地。SMTP 服務器就是遵循 SMTP 協議的發送郵件服務器。
- 了解常用郵件服務器(例如:QQ郵箱,網易郵箱,新浪郵箱,163郵箱…)
這里以QQ郵箱為例講解如何注冊郵件服務器:
首先需要注冊對應服務提供商免費郵箱,因為你要使用郵件服務提供商的SMTP,他們需要對身份進行驗證,這樣可以避免產生大量的垃圾郵件。
※ 注冊方式:打開QQ上的QQ郵箱,點擊設置,選擇賬號,找到POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服務,第一個pop3、SMTP服務,點擊后面的 開啟,會彈出密保驗證,根據要求發短信到號碼,發送至后會給你一個密碼(一定要記住此密碼,這是登陸的憑證)
相關參數:QQ郵箱STMP服務器地址為stmp.qq.com,端口為25(別的郵箱自行百度)
到此,注冊郵箱服務器就完成了。
- 接下來我們看如何用程序發送郵件
這里可以參考相關資料:
再次,附上自己的源代碼,僅供參考
需要導入命名空間 using System.Net.Mail;
public static void SendEmail() { //聲明一個Mail對象 MailMessage mymail = new MailMessage(); mymail.Attachments.Add(new Attachment("D:\\mail.txt")); //為該電子郵件添加附件 附件的路徑 //如果是多個附件 繼續.Add() mymail.Attachments.Add(new Attachment("C:\\mail.txt")); //發件人地址 //如是自己,在此輸入自己的郵箱 mymail.From = new MailAddress(“發件人郵箱號”) //收件人地址 mymail.To.Add(new MailAddress(“收件人郵箱號”)); //郵件主題 mymail.Subject = “郵件主題…”; //郵件標題編碼 mymail.SubjectEncoding = System.Text.Encoding.UTF8; //發送郵件的內容 mymail.Body =“郵件內容…”; //郵件內容編碼 mymail.BodyEncoding = System.Text.Encoding.UTF8; //抄送到其他郵箱 mymail.CC.Add(new MailAddress(“抄送郵箱號”)); //是否是HTML郵件 mymail.IsBodyHtml = true; //郵件優先級 mymail.Priority = MailPriority.High; //創建一個郵件服務器類 SmtpClient myclient = new SmtpClient(); myclient.Host = "SMTP.qq.com"; //qq郵箱服務器地址,不同的郵箱不同 //SMTP服務端口s myclient.Port = 25; myclient.EnableSsl = true; //驗證登錄 myclient.Credentials = new NetworkCredential(EmailKey, PasswordKey);//"@"輸入有效的郵箱名, "*"輸入有效的密碼(此密碼就是注冊郵箱服務器是發送短信后給的密碼) myclient.Send(mymail); Console.WriteLine("導出Excel成功!"); } 然而這種方法有一定的弊端,程序發布后,.cs文件不可編輯,而配置文件可以用記事本的方式打開編輯,所以跟數據庫的連接字符串一個性質,我們把相關可變的信息放到連接字符串。 在配置文件中進行以下操作: <appSettings> 節點添加以下內容:key value 的形式 <appSettings> <add key="FromKey" value="727472902@qq.com" /> <!—發件人 --> <!--如果發給多個人 改這里 NPOI 教程 http://www.cnblogs.com/atao/archive/2009/11/15/1603528.html "--> <add key="ToAddKey" value="727472902@qq.com" /> <!—收件人 --> <!—主題 --> <add key="SubjectKey" value="倉鮮智能便利店" /> <!—內容--> <add key="BodyKey" value="今日銷售報表相關情況" /> <!--抄送人--> <add key="CCAddKey" value="222222@qq.com" /> <!—郵箱服務器 --> <add key="EmailKey" value="222****222@qq.com" /> <!—郵箱服務器 密碼 --> <add key="PasswordKey" value="cau****yudhi" /> </appSettings> 接下來看看后台代碼如何使用它: public static void SendEmail() { //聲明一個Mail對象 MailMessage mymail = new MailMessage(); mymail.Attachments.Add(new Attachment(ExportExcelSaleDetail())); //為該電子郵件添加附件 mymail.Attachments.Add(new Attachment(ExportExcelStorage())); //發件人地址 //配置文件的方式讀取 在這里讀取配置文件中的內容 需要引入 //using System.Configuration; var FromKey = ConfigurationManager.AppSettings["FromKey"].ToString(); //對應配置文件中的key var ToAddKey = ConfigurationManager.AppSettings["ToAddKey"].ToString(); var SubjectKey = ConfigurationManager.AppSettings["SubjectKey"].ToString(); var BodyKey = ConfigurationManager.AppSettings["BodyKey"].ToString(); var CCAddKey = ConfigurationManager.AppSettings["CCAddKey"].ToString(); var EmailKey = ConfigurationManager.AppSettings["EmailKey"].ToString(); var PasswordKey = ConfigurationManager.AppSettings["PasswordKey"].ToString(); //----在這里用configuration 那個類 和讀取連接字符串似得 讀取剛才的key --- mymail.From = new MailAddress(FromKey); //收件人地址 mymail.To.Add(new MailAddress(ToAddKey)); //郵件主題 mymail.Subject = SubjectKey; //郵件標題編碼 mymail.SubjectEncoding = System.Text.Encoding.UTF8; //發送郵件的內容 mymail.Body = BodyKey; //郵件內容編碼 mymail.BodyEncoding = System.Text.Encoding.UTF8; //抄送到其他郵箱 mymail.CC.Add(new MailAddress(CCAddKey)); //是否是HTML郵件 mymail.IsBodyHtml = true; //郵件優先級 mymail.Priority = MailPriority.High; //創建一個郵件服務器類 SmtpClient myclient = new SmtpClient(); myclient.Host = "SMTP.qq.com"; //SMTP服務端口s myclient.Port = 25; myclient.EnableSsl = true; //驗證登錄 myclient.Credentials = new NetworkCredential(EmailKey, PasswordKey);//"@"輸入有效的郵件名, "*"輸入有效的密碼 myclient.Send(mymail); Console.WriteLine("導出Excel成功!"); } 再次發送郵件的相關內容就完成了…下面我們學習.net MVC + NPOI 導出Excel1.2導出Excel到定指路徑
1.去官網下載 NPOI相關dll文件:http://npoi.codeplex.com/downloads/get/1572743
2.在項目中添加引用
把Net40文件夾下的NPOI.Dll文件復制到自己的項目中的相關文件夾下,添加引用,瀏覽,找到剛剛的NPOI.Dll文件,確定
下面直接上代碼: public FileResult ExportExcel(string wareName, string date1, string date2) { //創建一個工作簿 NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook(); //添加一個sheet //創建一個頁 NPOI.SS.UserModel.ISheet sheet1 = book.CreateSheet("Sheet1"); //設置單元格 的寬高 sheet1.DefaultColumnWidth = 1 * 25; //寬度 sheet1.DefaultRowHeightInPoints = 25; //高度 //創建一行 IRow row = sheet1.CreateRow(0); //創建一列 ICell cell = row.CreateCell(0); ICellStyle cellStyle = book.CreateCellStyle();////創建樣式對象 IFont font = book.CreateFont(); //創建一個字體樣式對象 font.FontName = "方正舒體"; //和excel里面的字體對應 font.FontHeightInPoints = 16;//字體大小 font.Boldweight = short.MaxValue;//字體加粗 cellStyle.SetFont(font); //將字體樣式賦給樣式對象 cellStyle.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center;//垂直對齊 cellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;//水平對齊 cell.CellStyle = cellStyle; //把樣式賦給單元格 //給sheet1添加第一行的頭部標題 NPOI.SS.UserModel.IRow row1 = sheet1.CreateRow(0); row1.CreateCell(0).SetCellValue("商品編號"); row1.CreateCell(1).SetCellValue("商品名稱"); row1.CreateCell(2).SetCellValue("銷售數量"); row1.CreateCell(3).SetCellValue("商品售價"); row1.CreateCell(4).SetCellValue("出售總金額"); //將數據逐步寫入sheet1各個行 for (int i = 0; i < listSale.Count; i++) { NPOI.SS.UserModel.IRow rowtemp = sheet1.CreateRow(i + 1); //創建單元格並設置它的值 ID rowtemp.CreateCell(0).SetCellValue(listSale[i].waresCode); rowtemp.CreateCell(1).SetCellValue(listSale[i].waresName); rowtemp.CreateCell(2).SetCellValue(listSale[i].saleNum); rowtemp.CreateCell(3).SetCellValue(listSale[i].waresPrice.ToString()); rowtemp.CreateCell(4).SetCellValue(listSale[i].saleMoney.ToString()); } // 寫入到客戶端 System.IO.MemoryStream ms = new System.IO.MemoryStream(); book.Write(ms); ms.Seek(0, SeekOrigin.Begin); string a = DateTime.Now.ToString("yyyyMMddHHmmssffff");//這個路徑 有 :等符號,路徑不支持 //這里是導出到指定的路徑 string PPath = @"C:\Users\Administrator\Desktop\新建文件夾 (2)\Yuan\Manager\TestWinPlane\Excel\" + a + "商品銷售明細報表.xls"; using (FileStream fs = new FileStream(PPath, FileMode.Create, FileAccess.Write)) { byte[] datab = ms.ToArray(); fs.Write(datab, 0, datab.Length); fs.Flush(); } ms.Close(); ms.Dispose(); return File(ms, "application/vnd.ms-excel", a + "銷售明細統計.xls"); } }1.3 定時計划任務
1.新建項目à 創建控制台應用程序
把定時導出跟定時發送郵件的代碼寫在這里面:(下面直接上代碼)
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Manager.BLL; using NPOI.SS.UserModel; using System.IO; using System.Linq.Expressions; using System.Web; using System.Web.Mvc; using Manager; using System.Net; using System.Net.Mail; using System.Configuration; using System.Diagnostics; namespace TestWinPlane { public class Program { public static BaseBll<usersorder> bllorder { get { return new UsersOrderBll(); } } static Wares2Bll wareBll = new Wares2Bll(); public static UserBll userbll = new UserBll(); public static void Main(string[] args) { //這個里面寫你發送郵件的代碼 讓 win計划去執行他 Console.WriteLine("發送郵件!!"); ExportExcelSaleDetail(); ExportExcelStorage(); SendEmail(); //DeleteIO(); } //當前貨架商品統計 public static Manager.BLL.BaseBll2<wares> bll { get { return new Wares2Bll(); } } public class ListSalePro { public string waresCode { get; set; } public string waresName { get; set; } public decimal waresPrice { get; set; } //單價 public decimal saleMoney { get; set; } // 出售總金額 public int saleNum { get; set; } //出售數量 public decimal buyonePrice; public decimal buyMoney; public decimal ProfitMoney; } public class ListWare { public string waresCode { get; set; } public string waresName { get; set; } public long saleNum { get; set; } } static string a = DateTime.Now.ToString("yyyyMMddHHmm");//這個路徑 有 :等符號,路徑不支持 static string pathUnchange = @"C:\Excel\" + a; //導出的Excel 要存放的路徑 static string ExportExcelSaleDetailPath = "";//商品銷售明細報表路徑 static string ExportExcelStoragePath = "";//貨架上商品統計報表路徑 static OrderDetailsBll orderDetailBll = new OrderDetailsBll(); /// <summary> /// 當前貨架商品統計報表 /// </summary> /// <returns></returns> public static string ExportExcelStorage() { // 1.先篩選出 有效的商品 == 1 ? "有效" : "已下架" Expression<Func<wares, bool>> condition1 = x => x.validstatus == 1; var listCode = bll.Search2(condition1).Select(x => new { x.waresCode, x.waresName, x.waresActual, x.waresBid, x.waresPrice, x.waresSum, x.waresSpec, x.waresUnit, x.validstatus , x.waresWarning }).ToList(); //創建一個工作簿 NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook(); //添加一個sheet //創建一個頁 NPOI.SS.UserModel.ISheet sheet1 = book.CreateSheet("Sheet1"); //設置單元格 的寬高 sheet1.DefaultColumnWidth = 1 * 25; //寬度 sheet1.DefaultRowHeightInPoints = 25; //高度 //創建一行 IRow row = sheet1.CreateRow(0); //創建一列 ICell cell = row.CreateCell(0); ICellStyle cellStyle = book.CreateCellStyle();////創建樣式對象 IFont font = book.CreateFont(); //創建一個字體樣式對象 font.FontName = "方正舒體"; //和excel里面的字體對應 font.FontHeightInPoints = 16;//字體大小 font.Boldweight = short.MaxValue;//字體加粗 cellStyle.SetFont(font); //將字體樣式賦給樣式對象 //設置單元格的樣式:水平對齊居中 cellStyle.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center;//垂直對齊 cellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;//水平對齊 這兩個在這里不起作用 cell.CellStyle = cellStyle; //把樣式賦給單元格 //給sheet1添加第一行的頭部標題 NPOI.SS.UserModel.IRow row1 = sheet1.CreateRow(0); row1.CreateCell(0).SetCellValue("商品編號"); row1.CreateCell(1).SetCellValue("商品名稱"); row1.CreateCell(2).SetCellValue("商品售價"); row1.CreateCell(3).SetCellValue("商品進價"); row1.CreateCell(4).SetCellValue("商品單位"); row1.CreateCell(5).SetCellValue("商品規格"); row1.CreateCell(6).SetCellValue("貨架承載量 "); row1.CreateCell(7).SetCellValue("商品預警值"); row1.CreateCell(8).SetCellValue("當前貨架商品數量 "); // row1.CreateCell(9).SetCellValue("有效標志 "); //將數據逐步寫入sheet1各個行 for (int i = 0; i < listCode.Count; i++) { NPOI.SS.UserModel.IRow rowtemp = sheet1.CreateRow(i + 1); //創建單元格並設置它的值 ID rowtemp.CreateCell(0).SetCellValue(listCode[i].waresCode); rowtemp.CreateCell(1).SetCellValue(listCode[i].waresName); rowtemp.CreateCell(2).SetCellValue(listCode[i].waresPrice.ToString()); rowtemp.CreateCell(3).SetCellValue(listCode[i].waresBid.ToString()); rowtemp.CreateCell(4).SetCellValue(listCode[i].waresUnit); rowtemp.CreateCell(5).SetCellValue(listCode[i].waresSpec); rowtemp.CreateCell(6).SetCellValue(listCode[i].waresSum.ToString()); rowtemp.CreateCell(7).SetCellValue(listCode[i].waresWarning.ToString()); rowtemp.CreateCell(8).SetCellValue(listCode[i].waresActual.ToString()); // rowtemp.CreateCell(9).SetCellValue(listCode[i].validstatus==1?"有效":"已下架"); } // 寫入到客戶端 System.IO.MemoryStream ms = new System.IO.MemoryStream(); book.Write(ms); ms.Seek(0, SeekOrigin.Begin); string completePath = pathUnchange + "當前貨架商品報表.xls"; using (FileStream fs = new FileStream(completePath, FileMode.Create, FileAccess.Write)) { byte[] datab = ms.ToArray(); fs.Write(datab, 0, datab.Length); fs.Flush(); fs.Dispose(); } ms.Close(); ms.Dispose(); ExportExcelStoragePath = completePath; return ExportExcelStoragePath; } /// <summary> ///發送郵件 導入命名空間 using System.Net.Mail; /// </summary> public static void SendEmail() { //聲明一個Mail對象 MailMessage mymail = new MailMessage(); mymail.Attachments.Add(new Attachment(ExportExcelSaleDetailPath)); //為該電子郵件添加附件 mymail.Attachments.Add(new Attachment(ExportExcelStoragePath)); //發件人地址 //如是自己,在此輸入自己的郵箱 //配置文件的方式讀取 var FromKey = ConfigurationManager.AppSettings["FromKey"].ToString(); var ToAddKey = ConfigurationManager.AppSettings["ToAddKey"].ToString(); var SubjectKey = ConfigurationManager.AppSettings["SubjectKey"].ToString(); var BodyKey = ConfigurationManager.AppSettings["BodyKey"].ToString(); var CCAddKey = ConfigurationManager.AppSettings["CCAddKey"].ToString(); var EmailKey = ConfigurationManager.AppSettings["EmailKey"].ToString(); var PasswordKey = ConfigurationManager.AppSettings["PasswordKey"].ToString(); //----在這里用configuration 那個類 和讀取連接字符串似得 讀取剛才的key --- mymail.From = new MailAddress(FromKey); //收件人地址 mymail.To.Add(new MailAddress(ToAddKey)); //郵件主題 mymail.Subject = SubjectKey; //郵件標題編碼 mymail.SubjectEncoding = System.Text.Encoding.UTF8; //發送郵件的內容 mymail.Body = BodyKey; //郵件內容編碼 mymail.BodyEncoding = System.Text.Encoding.UTF8; //添加附件 //Attachment myfiles = new Attachment(tb_Attachment.PostedFile.FileName); //mymail.Attachments.Add(myfiles); //抄送到其他郵箱 mymail.CC.Add(new MailAddress(CCAddKey)); //是否是HTML郵件 mymail.IsBodyHtml = true; //郵件優先級 mymail.Priority = MailPriority.High; //創建一個郵件服務器類 SmtpClient myclient = new SmtpClient(); myclient.Host = "SMTP.qq.com"; //SMTP服務端口s myclient.Port = 25; myclient.EnableSsl = true; //驗證登錄 myclient.Credentials = new NetworkCredential(EmailKey, PasswordKey);//"@"輸入有效的郵件名, "*"輸入有效的密碼 myclient.Send(mymail); Console.WriteLine("導出Excel成功!"); } } }
2.代碼完成之后,運行看看能不能正常運行,正常之后 就該開始部署Windows計划任務了,
1.打開電腦的控制面板-->選擇小圖標-->管理工具-->任務計划程序-->新文件夾-->創建任務
2.選擇觸發器選項卡,點擊新建,根據自己的需求選擇執行的時間
3.選擇操作選項卡,點擊下方的新建,點擊瀏覽,選擇自己項目下的bin文件夾àDebugà選擇自己項項目的.exe文件,下面添加參數 可以忽略,點擊確定
4.還有條件 跟 設置選項卡,在這里根據需求自己選擇。
到此,定時導出跟發送郵件的相關信息就完成了。