using System;
using System.IO;
using System.Net;
using System.Net.Mail;
using NPOI.HSSF.UserModel; // 用于读取.xls文件
using NPOI.SS.UserModel;
class Program
{
static void Main(string[] args)
{
string excelFilePath = @"C:\Path\To\YourExcelFile.xls";
string emailFrom = "youremail@example.com";
string emailTo = "recipient@example.com";
string smtpServer = "smtp.example.com";
int smtpPort = 587;
string smtpUser = "smtpUsername";
string smtpPass = "smtpPassword";
try
{
// 读取Excel文件
var workbook = new HSSFWorkbook(File.ReadAllBytes(excelFilePath));
ISheet sheet = workbook.GetSheetAt(0); // 假设我们只处理第一个工作表
// 将Excel数据转换为HTML字符串
StringBuilder htmlBuilder = new StringBuilder("<table border='1'>");
for (int rowIndex = 0; rowIndex <= sheet.LastRowNum; rowIndex++)
{
IRow row = sheet.GetRow(rowIndex);
if (row != null)
{
htmlBuilder.Append("<tr>");
for (int cellIndex = 0; cellIndex <= row.LastCellNum; cellIndex++)
{
ICell cell = row.GetCell(cellIndex);
if (cell != null)
{
string cellValue = GetCellValueAsString(cell);
htmlBuilder.AppendFormat("<td>{0}</td>", WebUtility.HtmlEncode(cellValue));
}
}
htmlBuilder.Append("</tr>");
}
}
htmlBuilder.Append("</table>");
// 配置邮件
MailMessage message = new MailMessage
{
From = new MailAddress(emailFrom),
To = { emailTo },
Subject = "Excel Data as Email Body",
Body = htmlBuilder.ToString(),
IsBodyHtml = true
};
// 添加Excel文件作为附件
Attachment attachment = new Attachment(excelFilePath);
message.Attachments.Add(attachment);
// 使用SMTP发送邮件
SmtpClient client = new SmtpClient(smtpServer, smtpPort)
{
Credentials = new NetworkCredential(smtpUser, smtpPass),
EnableSsl = true
};
client.Send(message);
Console.WriteLine("Email sent successfully.");
}
catch (Exception ex)
{
Console.WriteLine("Error sending email: " + ex.Message);
}
}
static string GetCellValueAsString(ICell cell)
{
switch (cell.CellType)
{
case CellType.Numeric:
return cell.NumericCellValue.ToString();
case CellType.String:
return cell.StringCellValue;
case CellType.Boolean:
return cell.BooleanCellValue.ToString();
case CellType.Blank:
return "";
// 可能需要处理更多类型,如日期等
default:
throw new NotSupportedException($"Cell type {cell.CellType} is not supported.");
}
}
}