杂项收集,包括-发邮件、二维码生成、文件下载、压缩、导出excel
本篇就最近工作解决的问题做个代码收集。包括以下几个方面:发邮件、二维码生成、文件下载、压缩、导出excel。有一种可用的解决方法就好,不求全面,不求原理。
1、发邮件:
命名空间:System.Net.Mail
程序集:System(在 system.dll 中)
tips: MailMessage 类的实例用于构造可使用 SmtpClient 类传输到 SMTP 服务器以便传递的电子邮件。
若要指定电子邮件的发件人、收件人和内容,请使用 MailMessage 类的关联属性。一般需要注意的有 发件人From、收件人To、抄送 (CC)、密件抄送 (BCC)、附件Attachments、主题Subject、邮件正文Body。
另外,测试时正文和标题不要随意输入类似"afdadva"等等的无意义字母数字,会被服务器默认为垃圾邮件而拦截。
1 string senderServerIp = "smtp.126.com"; 2 3 string fromMailAddress = "xxx@126.com"; 4 string mailUsername = "xxx@126.com"; 5 string mailPassword = "pppp"; //发送邮箱的密码 6 string mailPort = "25"; 7 string attachPath = path + "/" + fileName;//附件 8 parmer.Content = "该邮件由系统代发."; 9 MailHelper email = new MailHelper(senderServerIp, parmer.ReceiveMailbox, fromMailAddress, 10 parmer.Title, parmer.Content, mailUsername, mailPassword, mailPort, false, true); 11 email.AddAttachments(attachPath); 12 email.Send();
1 using System; 2 using System.IO; 3 using System.Net.Mail; 4 using System.Net.Mime; 5 6 namespace NewEnergyHandler.Common 7 { 8 public class MailHelper 9 { 10 private readonly MailMessage _mMailMessage; //主要处理发送邮件的内容(如:收发人地址、标题、主体、图片等等) 11 private SmtpClient _mSmtpClient; //主要处理用smtp方式发送此邮件的配置信息(如:邮件服务器、发送端口号、验证方式等等) 12 private readonly int _mSenderPort; //发送邮件所用的端口号(htmp协议默认为25) 13 private readonly string _mSenderServerHost; //发件箱的邮件服务器地址(IP形式或字符串形式均可) 14 private readonly string _mSenderPassword; //发件箱的密码 15 private readonly string _mSenderUsername; //发件箱的用户名(即@符号前面的字符串,例如:hello@163.com,用户名为:hello) 16 private readonly bool _mEnableSsl; //是否对邮件内容进行socket层加密传输 17 private readonly bool _mEnablePwdAuthentication; //是否对发件人邮箱进行密码验证 18 19 ///<summary> 20 /// 构造函数 21 ///</summary> 22 ///<param name="server">发件箱的邮件服务器地址</param> 23 ///<param name="toMail">收件人地址(可以是多个收件人,程序中是以“;"进行区分的)</param> 24 ///<param name="fromMail">发件人地址</param> 25 ///<param name="subject">邮件标题</param> 26 ///<param name="emailBody">邮件内容(可以以html格式进行设计)</param> 27 ///<param name="username">发件箱的用户名(即@符号前面的字符串,例如:hello@163.com,用户名为:hello)</param> 28 ///<param name="password">发件人邮箱密码</param> 29 ///<param name="port">发送邮件所用的端口号(htmp协议默认为25)</param> 30 ///<param name="sslEnable">true表示对邮件内容进行socket层加密传输,false表示不加密</param> 31 ///<param name="pwdCheckEnable">true表示对发件人邮箱进行密码验证,false表示不对发件人邮箱进行密码验证</param> 32 public MailHelper(string server, string toMail, string fromMail, string subject, string emailBody, string username, string password, string port, bool sslEnable, bool pwdCheckEnable) 33 { 34 try 35 { 36 _mMailMessage = new MailMessage(); 37 _mMailMessage.To.Add(toMail); 38 _mMailMessage.From = new MailAddress(fromMail); 39 _mMailMessage.Subject = subject; 40 _mMailMessage.Body = emailBody; 41 _mMailMessage.IsBodyHtml = true; 42 _mMailMessage.BodyEncoding = System.Text.Encoding.UTF8; 43 _mMailMessage.Priority = MailPriority.Normal; 44 _mSenderServerHost = server; 45 _mSenderUsername = username; 46 _mSenderPassword = password; 47 _mSenderPort = Convert.ToInt32(port); 48 _mEnableSsl = sslEnable; 49 _mEnablePwdAuthentication = pwdCheckEnable; 50 } 51 catch (Exception ex) 52 { 53 Console.WriteLine(ex.ToString()); 54 } 55 } 56 57 ///<summary> 58 /// 添加附件 59 ///</summary> 60 ///<param name="attachmentsPath">附件的路径集合,以分号分隔</param> 61 public void AddAttachments(string attachmentsPath) 62 { 63 try 64 { 65 string[] path = attachmentsPath.Split(';'); //以什么符号分隔可以自定义 66 for (int i = 0; i < path.Length; i++) 67 { 68 var data = new Attachment(path[i], MediaTypeNames.Application.Octet); 69 var disposition = data.ContentDisposition; 70 disposition.CreationDate = File.GetCreationTime(path[i]); 71 disposition.ModificationDate = File.GetLastWriteTime(path[i]); 72 disposition.ReadDate = File.GetLastAccessTime(path[i]); 73 disposition.FileName = path[i].Substring(path[i].LastIndexOf('/')+1); 74 _mMailMessage.Attachments.Add(data); 75 } 76 } 77 catch (Exception ex) 78 { 79 Console.WriteLine(ex.ToString()); 80 } 81 } 82 83 ///<summary> 84 /// 邮件的发送 85 ///</summary> 86 public void Send() 87 { 88 try 89 { 90 if (_mMailMessage != null) 91 { 92 _mSmtpClient = new SmtpClient 93 { 94 Host = _mSenderServerHost, 95 Port = _mSenderPort, 96 UseDefaultCredentials = false, 97 EnableSsl = _mEnableSsl 98 }; 99 if (_mEnablePwdAuthentication) 100 { 101 System.Net.NetworkCredential nc = new System.Net.NetworkCredential(_mSenderUsername, _mSenderPassword); 102 _mSmtpClient.Credentials = nc.GetCredential(_mSmtpClient.Host, _mSmtpClient.Port, "NTLM"); 103 } 104 else 105 { 106 _mSmtpClient.Credentials = new System.Net.NetworkCredential(_mSenderUsername, _mSenderPassword); 107 } 108 _mSmtpClient.DeliveryMethod = SmtpDeliveryMethod.Network; 109 _mSmtpClient.Send(_mMailMessage); 110 } 111 } 112 catch (Exception ex) 113 { 114 Console.WriteLine(ex.ToString()); 115 } 116 } 117 } 118 }
2、二维码生成
命名空间:using ThoughtWorks.QRCode.Codec;
程序集:ThoughtWorks.QRCode.dll(需从网上下载)。
tips: QRCodeEncoder类设置一下生成相关的参数,而后 确定二维码里的内容,以及要保存的文件名和路径即可。
QrCodeHelper qrCodeHelper =new QrCodeHelper(); var qrCodeFilePath = qrCodeHelper.CreateCode_Simple("testString.");
using System; using System.Drawing; using System.IO; using System.Text; using ThoughtWorks.QRCode.Codec; namespace Common { public class QrCodeHelper { public string CreateNr(int id) { return id.ToString(); } //程序路径 readonly string _currentPath = ConfigHelper.GetConfigString("QrCodePicPath"); public string CreateCode_Simple(int scale, string nr) { var qrCodeEncoder = new QRCodeEncoder { QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE, QRCodeScale = scale, QRCodeVersion = 0, QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M }; Image image = qrCodeEncoder.Encode(nr, Encoding.UTF8); //文件名 var fileName = DateTime.Now.ToString(@"yyyymmddhhmmssfff"); SaveImg(_currentPath, fileName + ".jpg", image); image.Dispose(); return fileName; } public string CreateCode_Simple(string nr) { return CreateCode_Simple(4, nr); } /// <summary> /// 保存图片 /// </summary> /// <param name="strPath">保存路径</param> /// <param name="fileName"></param> /// <param name="img">图片</param> public static void SaveImg(string strPath, string fileName, Image img) { //保存图片到目录 if (!Directory.Exists(strPath)) { //当前目录不存在,则创建 Directory.CreateDirectory(strPath); } img.Save(strPath + "/" + fileName, System.Drawing.Imaging.ImageFormat.Jpeg); } } }
3、文件下载
网站下载一般就是Response里写入文件,注意下文件的后缀,类型匹配就ok。
1 var response = HttpContext.Response; 2 response.Clear(); 3 response.Buffer = true; 4 response.Charset = "utf-8"; 5 var file1 = "xxx.dll"; 6 response.AppendHeader("Content-Disposition", "attachment;filename=" + file1); 7 response.ContentEncoding = System.Text.Encoding.UTF8; 8 response.ContentType = "application/x-msdownload"; 9 var pathTest = "D:/CommonTest"; 10 response.WriteFile(pathTest + "/" + file1); 11 response.End();
4、压缩
这篇博文详细明了:.NET 4.5 中新提供的压缩类
5、导出excel
命名空间:using Aspose.Cells;
程序集:Aspose.Cells.dll
tips:Aspose可以脱离微软的excel,方便使用。
var workbook = new Workbook(); var sheet = workbook.Worksheets[0]; var colIndex = "A"; string title = "名称,分类,编号,单位,数量,状态,责任人,部门,时间"; string[] titleList=title.Split(','); foreach (string item in titleList) { sheet.Cells[colIndex + 1].PutValue(item); sheet.Cells[colIndex + 1].SetStyle(styleTitle); colIndex = ((char)(colIndex[0] + 1)).ToString(); } workbook.Save(file);
int row = 2; int column; foreach (var d in data) { column = 0; var model= d as Model; if (model== null) continue; //和你的标题对应好就行。 sheet.Cells[row, column].PutValue(model.Name); sheet.Cells[row, column++].SetStyle(styleBody);//设置样式 }
如果是单条数据要做一个卡片的excel,可以先写个模版,然后打开模版,填充数据。我遇到过把不同类型的数据都做成卡片,添加到一个个sheet里。
var workbookResult = new Workbook(); var workbookType1 = new Workbook(); var workbookType2 = new Workbook(); var workbookType3 = new Workbook(); workbookType1.Open(path + "/type1.xlsx"); workbookType2.Open(path + "/type2.xlsx"); workbookType3.Open(path + "/type3.xlsx"); Worksheet sheet; if(type=type1) { sheet = workbookType1.Worksheets[0]; var cells = sheet.Cells; //单元格 //todo: 填充你的数据到cells. } else if(..){} else if(..){} workbookResult.Worksheets.Add(); //新增一个sheet var sheetR = workbook.Worksheets[i++]; sheetR.Copy(sheet); //将生成的结果拷贝到新的sheet中 workbookResult.Save(fileName);
var path = ConfigHelper.GetConfigString("PicFilePath"); var image = Image.FromFile(path + "/" + asset.PicFile); var ms = new MemoryStream(); image.Save(ms, ImageFormat.Jpeg); sheet.Pictures.Add(24, 0, 41, 5, ms); //左上角 和 右下角 的下标
另注:以上用到的代码,很多都是网上搜索而来,并非原创,工作匆忙,未能保存原链接。若是原作者觉得侵权,删之。
结语:我只想把我所知道的,尽量简洁清楚地表达出来。