记录工作中遇到发邮件带附件的需求,新建控制台应用程序,目录下创建好所需要的定义好的Excel模板!

class Program
{
static string newExcelPath = string.Empty;
static string fileName = string.Empty; static void Main(string[] args)
{
CopyReportTemplate();
ExportDataToExcel();
SendEmail();
} #region 复制 Excel 模板 -- void CopyReportTemplate()
/// <summary>
/// 复制 Excel 模板
///
/// ++++++++++++++++++++++++++++++++++++++++++++
/// liam 2021.03.9
/// 获取应用程序的当前工作目录。
/// System.IO.Directory.GetCurrentDirectory()
/// 获取启动了应用程序的可执行文件的路径。
/// System.Windows.Forms.Application.StartupPath
/// +++++++++++++++++++++++++++++++++++++++++++++
///
/// </summary>
private static void CopyReportTemplate()
{
string excelTemplatePath = System.Windows.Forms.Application.StartupPath + "\\出行申报报表.xlsx";
//Directory.GetCurrentDirectory() + "\\出行报表.xlsx";
string str = DateTime.Now.ToString("yyyyMMdd");
fileName = "出行申报报表-" + str; newExcelPath =System.Windows.Forms.Application.StartupPath + "\\Report\\" + fileName + ".xlsx";
//Directory.GetCurrentDirectory() + "\\Report\\" + fileName + ".xlsx";
File.Delete(newExcelPath);
File.Copy(excelTemplatePath, newExcelPath);
}
#endregion #region 获取报表数据 -- DataSet GetReportData()
/// <summary>
/// 获取报表数据
/// </summary>
/// <returns></returns>
private static DataSet GetReportData()
{
DataSet ds = new DataSet();
string sql0 = "pc_Select_CheckHolidayInformationData_No";
string date = DateTime.Now.ToString("yyyy-MM-dd");
SqlParameter[] sp = {
new SqlParameter("@date",date)
};
DataTable table0 = GetDataTable(CommandType.StoredProcedure, sql0, sp);
table0.TableName = "未申报记录";
string sql1 = "pc_Select_CheckHolidayInformationData_Yes";
DataTable table1 = GetDataTable(CommandType.StoredProcedure, sql1);
table1.TableName = "已申报记录";
ds.Tables.Add(table0);
ds.Tables.Add(table1); return ds;
}
#endregion #region 导出数据至 Excel -- static void ExportDataToExcel()
/// <summary>
/// 导出数据至 Excel
/// </summary>
private static void ExportDataToExcel()
{
XSSFWorkbook workbook = null;
using (FileStream file = new FileStream(newExcelPath, FileMode.Open, FileAccess.Read))
{
workbook = new XSSFWorkbook(file);
file.Close();
}
ICellStyle style = CellStyle(workbook);
ICellStyle styleRed = CellStyle(workbook);
styleRed.FillPattern = FillPattern.SolidForeground;
styleRed.FillForegroundColor = HSSFColor.Coral.Index;
DataSet ds = GetReportData();
for (int i = 0; i < ds.Tables.Count; i++)
{
DataTable table = ds.Tables[i];
ISheet sheet = workbook.GetSheet(table.TableName);
for (int j = 0; j < table.Rows.Count; j++)
{
IRow row = sheet.CreateRow(1 + j);
row.Height = 18 * 20; for (int k = 0; k < table.Columns.Count; k++)
{
string colName = table.Columns[k].ColumnName;
string str = CheckFieldIsNullOrEmpty(table, j, colName);
ICell cell = row.CreateCell(k);
cell.SetCellValue(str);
}
}
}
using (FileStream fs = new FileStream(newExcelPath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
{
workbook.Write(fs);
fs.Close();
}
}
#endregion #region 创建 Excel 单元格样式 -- ICellStyle CellStyle(XSSFWorkbook workbook)
/// <summary>
/// 创建 Excel 单元格样式
/// </summary>
/// <param name="workbook"></param>
/// <returns></returns>
private static ICellStyle CellStyle(XSSFWorkbook workbook)
{
IFont fontAll = workbook.CreateFont();
fontAll.FontName = "Microsoft YaHei";
fontAll.FontHeight = 10 * 20;
ICellStyle ItemCellStyle = workbook.CreateCellStyle();
ItemCellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
ItemCellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
ItemCellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
ItemCellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
ItemCellStyle.BottomBorderColor = HSSFColor.Grey25Percent.Index;
ItemCellStyle.LeftBorderColor = HSSFColor.Grey25Percent.Index;
ItemCellStyle.RightBorderColor = HSSFColor.Grey25Percent.Index;
ItemCellStyle.TopBorderColor = HSSFColor.Grey25Percent.Index;
ItemCellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Left;
ItemCellStyle.VerticalAlignment = VerticalAlignment.Center;
ItemCellStyle.SetFont(fontAll);
return ItemCellStyle;
}
#endregion #region 检查 Table CELL 数据 -- string CheckFieldIsNullOrEmpty(DataTable table, string key)
/// <summary>
/// 检查 Table CELL 数据
/// </summary>
/// <param name="table"></param>
/// <param name="key"></param>
/// <returns></returns>
public static string CheckFieldIsNullOrEmpty(DataTable table, string key)
{
string value = string.Empty;
if (table != null && table.Rows.Count > 0)
{
if (!string.IsNullOrEmpty(table.Rows[0][key].ToString()))
{
value = table.Rows[0][key].ToString();
}
}
return value;
} /// <summary>
/// 检查 Table CELL 数据
/// </summary>
/// <param name="table"></param>
/// <param name="rowIndex"></param>
/// <param name="key"></param>
/// <returns></returns>
public static string CheckFieldIsNullOrEmpty(DataTable table, int rowIndex, string key)
{
string value = string.Empty;
if (table != null && table.Rows.Count > 0)
{
if (!string.IsNullOrEmpty(table.Rows[rowIndex][key].ToString()))
{
value = table.Rows[rowIndex][key].ToString();
}
}
return value;
}
#endregion #region 发送邮件 -- static void SendEmail()
/// <summary>
/// 发送邮件
/// </summary>
private static void SendEmail()
{
//string sql = "pc_SendEmail_CheckUserReport";
//SqlParameter[] sp = {
// new SqlParameter("@path",newExcelPath),
// new SqlParameter("@fileName",fileName)
//};
//int i = NonQuery(CommandType.StoredProcedure, sql, sp); //设置邮件的服务器
string host = "IP地址";
//替换成你的hotmail账户
string mailAddress = "发邮件地址";
//目标邮件地址。可添加多个地址,逗号分隔
string[] ToAddress = { "目标邮件地址" };
string[] CcAddress = { "抄送邮件地址" }; SmtpClient smtp = new SmtpClient(host);
smtp.EnableSsl = false; //开启安全连接。
smtp.DeliveryMethod = SmtpDeliveryMethod.Network; //使用网络传送
StringBuilder sb = new StringBuilder();
sb.AppendLine("<span style='font-family:Arial; font-size: 13px; '>Dear All:</span><br/><br/>");
sb.AppendLine("<div style='font-family:Microsoft YaHei UI;font-size: 13px; padding-left:100px; width:300px;'> 出行申报情况,请查阅附件,谢谢。</div>");
sb.AppendLine("<br/><span style='font-family:Arial;font-size: 13px; '> Best regards, CMOA System;</ span ><br/> ");
sb.AppendLine("<span style='font-family:Arial;font-size: 13px;'>This is auto-generated email, please do not reply. Thank you for your attention !<br/></span><br/><br/>");
MailMessage message = new MailMessage(); //创建邮件
message.From = new MailAddress(mailAddress);
message.Subject = fileName;
message.IsBodyHtml = true;
for (int i = 0; i < ToAddress.Length; i++)
{
message.To.Add(ToAddress[i]);
}
for (int i = 0; i < CcAddress.Length; i++)
{
message.CC.Add(CcAddress[i]);
}
message.Body = sb.ToString(); //string newExcelPath = @"D:\MID PDF.zip"; string MIME = MimeMapping.GetMimeMapping(newExcelPath);//文件的MediaType MIME
//message.AlternateViews.Add(new AlternateView(fileAddress,MIME)); //发送附加内容(附加的内容为文件中的内容) //发送附加件
message.Attachments.Add(new Attachment(newExcelPath, MIME));
smtp.Send(message); //发送邮件
}
#endregion #region DataTable -- static DataTable GetDataTable(CommandType cmdType, string cmdText, params SqlParameter[] cmdParams)
/// <summary>
/// DataTable
/// </summary>
/// <param name="cmdType"></param>
/// <param name="cmdText"></param>
/// <param name="cmdParams"></param>
/// <returns></returns>
public static DataTable GetDataTable(CommandType cmdType, string cmdText, params SqlParameter[] cmdParams)
{
DateTime starttime = DateTime.Now; //起始时间
using (SqlConnection Connection = new SqlConnection("Server=IP地址;DataBase=库名;Uid=账号;Pwd=密码"))
{
DataTable dt = new DataTable();
Connection.Open();
SqlDataAdapter da = new SqlDataAdapter(cmdText, Connection);
try
{
da.SelectCommand.CommandTimeout = 300;
da.SelectCommand.CommandType = cmdType; //设置命令类型
da.SelectCommand.Parameters.AddRange(cmdParams);
da.Fill(dt); return dt; }
catch (System.Exception ex)
{
Console.WriteLine(ex.Message);
da.Dispose();
Connection.Close();
return null;
}
finally
{
Connection.Close();
Connection.Dispose();
}
}
}
#endregion #region 执行数据的增、删、改方法 -- static int NonQuery(CommandType type, string CommandText, string sysName, params SqlParameter[] pars)
/// <summary>
/// 执行数据的增、删、改方法
/// </summary>
/// <param name="type">要执行的数据库命令类型</param>
/// <param name="CommandText">要执行的SQL语句或存储过程</param>
/// <param name="pars">所需的参数列表</param>
/// <returns>受影响的行数</returns>
public static int NonQuery(CommandType type, string CommandText, params SqlParameter[] pars)
{
DateTime starttime = DateTime.Now; //起始时间
int i = 0;
using (SqlConnection Connection = new SqlConnection("Server=IP地址;DataBase=库名;Uid=账号;Pwd=密码"))
{
Connection.Open();
//实例化数据库命令对象
SqlCommand cmd = new SqlCommand(CommandText, Connection);
try
{
cmd.CommandTimeout = 0;
//设置命令执行类型
cmd.CommandType = type;
//设置SQL语句或存储过程参数
SqlParameter[] sp = new SqlParameter[pars.Length];
sp = pars;
cmd.Parameters.AddRange(sp);
//调用方法得到SqlDataReader对象
i = cmd.ExecuteNonQuery(); return i;
}
catch (Exception err)
{
cmd.Dispose();
Connection.Close();
throw new Exception(err.Message);
}
finally
{
Connection.Close();
Connection.Dispose();
}
}
}
#endregion
}

C#发送邮件,可带有Excel附件的更多相关文章

  1. Python模块探秘 Smtplib发送带有各种附件的邮件

    这两天对Python的邮件模块比较感兴趣,于是就查了查资料.同时在实际的编码过程中也遇到了各种各样的问题.下面我就来分享一下我与smtplib的故事. 前提条件 我的上一篇博文里面讲解了,发送邮件必须 ...

  2. C# 解决 邮件发送Excel附件后,excel处于锁定状态

    当使用c#自带的MailMessage类发送excel附件时,再次打开excel会提示处于锁定状态. 解决思路:Attachment是添加附件的类,邮件发送后没有释放该类 public string ...

  3. ci框架(codeigniter)Email发送邮件、收件人、附件、Email调试工具

        ci框架(codeigniter)Email发送邮件.收件人.附件.Email调试工具 Email 类         CodeIgniter 拥有强大的 Email 类来提供如下的功能: 多 ...

  4. python3使用smtplib发送邮件,带xlsx附件

    一.概述 最近在做一个统计报表,需要发送邮件,并带附件的. 在之前的文章中 https://www.cnblogs.com/xiao987334176/p/10022026.html 已经实现了发送邮 ...

  5. 个人永久性免费-Excel催化剂功能第24波-批量发送邮件并指点不同附件不同变量

    批量发送邮件功能,对高级OFFICE用户来说,第1时间会想到使用WORD的邮件合并功能.但对于需要发送附件来说,邮件合并功能就无能为力,同样还有的限制是用户电脑上没有安装OUTLOOK,同样也不能发送 ...

  6. 基于PHP自带的mail函数实现发送邮件以及带有附件的邮件功能

    PHPmail函数简介 bool mail ( string $to , string $subject , string $message [, string $additional_headers ...

  7. android--email发送邮件,文本还有附件形式的邮件

    1.首先用的jar包为javaemail 下载地址: https://yunpan.cn/cB3kY8WIvcGtU (提取码:e042) 2.工具包 package com.kllayhello.u ...

  8. Java使用javax.mail.jar发送邮件并同意发送附件

    因为Java在开发网页上占有绝大优势.所以作为web端的领军人物,譬如发送短信和发送邮件这些就成了必定,网络安全一再安全我们须要把账号的安全级别提到更高.因此这些对于开发者也就成了必须掌握的技能!我一 ...

  9. Android简单发送邮件(可带附件)

    项目中遇到了一个发送邮件的功能,在网上查了很多,资料也很多.这里就不一一介绍了,只是写出我使用的方案(最简单的) Intent email = new Intent(android.content.I ...

随机推荐

  1. 当Hobject类型出现内存泄漏爆炸增长的问题,怎么处理

    尝试使用get,和set(在拍照之后,调用set,在obj使用前释放资源的思想来完成) HObject Get_inputImage() { return inputImage; } void Set ...

  2. js instanceof 解析

    js中的instanceof运算符 概述 instanceof运算符用来判断一个构造函数的prototype属性所指向的对象是否存在另外一个要检测对象的原型链上 语法 obj instanceofOb ...

  3. python-字符串操作分类小结

    切片 str[start:end:step] # 包括头,不包括尾巴.step为步长,意思是每隔step-1个元素,取一个字符 [::-1] #反向取字符串,实现字符串的反转 "abcde& ...

  4. SSH 远程访问及控制 ( 早上好,我是派大星,上帝派来爱你的那颗星)

    远程访问及控制 1.SSH远程管理,TCP Wrappers访问控制 2.配置密钥对验证 1.SSH远程管理,TCP访问控制 SSH是一种安全通道协议,主要用来实现字符界面的远程登录.远程复制等功能: ...

  5. 数值分析:最小二乘与岭回归(Pytorch实现)

    Chapter 4 1. 最小二乘和正规方程 1.1 最小二乘的两种视角 从数值计算视角看最小二乘法 我们在学习数值线性代数时,学习了当方程的解存在时,如何找到\(\textbf{A}\bm{x}=\ ...

  6. 「Python实用秘技05」在Python中妙用短路机制

    本文完整示例代码及文件已上传至我的Github仓库https://github.com/CNFeffery/PythonPracticalSkills 这是我的系列文章「Python实用秘技」的第5期 ...

  7. Solution -「多校联训」最大面积

    \(\mathcal{Description}\)   Link.   平面上有 \(n\) 个点 \(A_{1..n}\),\(q\) 次询问,每次给出点 \(P\),求 \[\max_{1\le ...

  8. Solution -「CF 1392G」Omkar and Pies

    \(\mathcal{Description}\)   Link.   给定两个长度为 \(K\) 的 \(01\) 串 \(S,T\) 和 \(n\) 组操作 \((a_i,b_i)\),意义为交换 ...

  9. python 定时任务apscheduler的使用

    apscheduler 的使用   我们项目中总是避免不了要使用一些定时任务,比如说最近的项目,用户点击报名考试以后需要在考试日期临近的时候推送小程序消息提醒到客户微信上,翻了翻 fastapi 中的 ...

  10. CPU使用率过高怎么办

    实际上前文中关于CPU使用率过高如何通过各种工具获得相关的热点进程.那么进程有了,那得疑惑到底哪个哪段代码导致了这个进程成为热点呢? 如果在调试阶段,可以使用gdb中断运行,但是在生产环境肯定不行.L ...