记录工作中遇到发邮件带附件的需求,新建控制台应用程序,目录下创建好所需要的定义好的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. HCNP Routing&Switching之组播技术-IGMP-Snooping

    前文我们了解了组播协议IGMP相关话题,回顾请参考https://www.cnblogs.com/qiuhom-1874/p/15700550.html:今天我们来聊一聊二层交换机处理组播报文所面临的 ...

  2. 1.Flink实时项目前期准备

    1.日志生成项目 日志生成机器:hadoop101 jar包:mock-log-0.0.1-SNAPSHOT.jar gmall_mock ​ |----mock_common ​ |----mock ...

  3. 面向计算机视觉的深度学习 | iBooker&#183;ApacheCN

    原文:Deep Learning for Computer Vision 协议:CC BY-NC-SA 4.0 自豪地采用谷歌翻译 不要担心自己的形象,只关心如何实现目标.--<原则>,生 ...

  4. AT2689 [ARC080D] Prime Flip

    简要题解如下: 区间修改问题,使用差分转化为单点问题. 问题变成,一开始有 \(2n\) 个点为 \(1\),每次操作可以选择 \(r - l\) 为奇质数的两个点 \(l, r\) 使其 ^ \(1 ...

  5. Html设置文本换行与不按行操作

    图片来源:W3C 部分引自大佬:https://zhidao.baidu.com/question/424920602093167052.html 强制不换行 div{ white-space:now ...

  6. Android返回键

    感谢大佬:https://www.cnblogs.com/qiluboy/p/5308310.html Android中back键和home键的区别: back键 Android的程序无需刻意的去退出 ...

  7. ansible学习(一)

    基础概念 ansible是什么? 它是一个"配置管理工具",它是一个"自动化运维工具",如果你没有使用过任何配置管理工具,不要害怕,看完这篇文章,你自然会对an ...

  8. 电脑预装Office2016打开Word时点击保存弹出“word无法启动转换器RECOVR32.CNV”对话框问题的修复方法

    感谢大佬:https://blog.csdn.net/qq_41969790/article/details/85161701 1.问题描述:电脑预装的Office2016,家庭和学生版正版.每次打开 ...

  9. js对于客户端的区分代码

    //区分设备 function judge_decice() { let ua =navigator.userAgent.toLowerCase(); if(/android|adr/gi.test( ...

  10. 为什么后台给前台Date是时间戳,而前台给后台则直接是时间字符串?

    一.因为时间的格式有很多种,不同的页面可能对不同的时间显示需求不同.比如: 05-8-8 上午9:17 2005-8-8 9:17:42 2005年8月8日 上午09时17分42秒 2005年8月8日 ...