记录工作中遇到发邮件带附件的需求,新建控制台应用程序,目录下创建好所需要的定义好的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. HUWEI交换机如何判断环路故障

    定义 以太网交换网络中为了提高网络可靠性,通常会采用冗余设备和冗余链路,然而现网中由于组网调整.配置修改.升级割接等原因,经常会造成数据或协议报文环形转发,不可避免的形成环路.如图1所示,三台设备两两 ...

  2. NOIP2018 Day2T2 填数游戏

    下面先给出大家都用的打表大法: 首先我们可以发现 \(n \le 3\) 的情况有 \(65pts\),而 \(n\) 这么小,打一下表何乐而不为呢?于是我写了一个爆枚每个位置再 \(check\) ...

  3. new Date时间格式转换方法

    平时经常会使用到时间转换,组件库已经有很多组件可以自动生成时间类型了,但是底层的封装方法还是得有 获取当前时间 new Date()  或者自己拥有一个毫秒时间 方法如下 /** * title: 时 ...

  4. Java 中使用正则表达式校检IP是否输入正确

    感谢大佬案例:https://www.jb51.net/article/114671.htm 正则表达式学习:(待办)近期总结

  5. Swift 学习网址精选 By HL

    虽然目前iOS大部分的项目开发语言用的不是Swift,但随着Swift的不断强大,取代Objective-C 指日可待,所以学习Swift是十分必要的.但毕竟是亲儿子,目前只有Foundation被翻 ...

  6. pyrealsense2学习

    如何得到realsense设备信息 前提:将D455连接在电脑上,并且已经下载好 Realsense Viewer 打开Realsense Viewer--> Info, 便可得到相机的一些参数 ...

  7. mybatis中的#和$的使用规范

    MyBatis 中 #{} 和 ${} 的区别 1.在MyBatis 的映射配置文件中,动态传递参数有两种方式: (1)#{} 占位符 (2)${} 拼接符 2.#{} 和 ${} 的区别 (1) 1 ...

  8. JTAG 标准IEEE STD 1149.1-2013学习笔记(一·)Test logic architecture、Instruction register以及Test data registers

    我是 雪天鱼,一名FPGA爱好者,研究方向是FPGA架构探索和SOC设计. 关注公众号[集成电路设计教程],拉你进"IC设计交流群". 注:转载请注明出处 一.Test logic ...

  9. 使用PHP利用phpmailer发送电子邮件

    先来几句废话:    phpMailer是一个非常强大的php发送邮件类,可以设定发送邮件地址.回复地址.邮件主题.html网页,上传附件,并且使用起来非常方便.     phpMailer的特点:  ...

  10. 四、MyBatis注解开发

    MyBatis中提供注解有: @Insert:实现新增 @Update:实现更新 @Delete:实现删除 @Select:实现查询 @Result:实现结果集封装 @Results:可以与@Resu ...