gpt4 book ai didi

c# - 在 c# 中从数据表发送带有 excel 作为附件的电子邮件

转载 作者:行者123 更新时间:2023-12-04 22:30:14 26 4
gpt4 key购买 nike

我有一个数据表。我想将数据表的内容作为 excel 发送,并将电子邮件作为附件发送。我尝试了下面的代码,但它正在发送 expty excel 文件。

首先,我将数据表转换为流对象,并将流传递给带有其他邮件参数的 sendemail 方法。

 private static Stream DataTableToStream(System.Data.DataTable table)
{
const string semiColon = ";";

var ms = new MemoryStream();
var sw = new StreamWriter(ms);

foreach (DataColumn column in table.Columns)
{
sw.Write(column.ColumnName);
sw.Write(semiColon);
}
sw.Write(Environment.NewLine);
foreach (DataRow row in table.Rows)
{
for (int i = 0; i < table.Columns.Count; i++)
{
sw.Write(row[i].ToString().Replace(semiColon, string.Empty));
sw.Write(semiColon);
}
sw.Write(Environment.NewLine);
}
return ms;
}

下面是发送邮件代码
 private const string ExcelContentType = "application/ms-excel";

private static bool SendMail(MailAddress from, string to, string[] CCAddress, String strSubject, String strBody, Attachment attachment, Stream tableStream)
{
try
{
const string attchmentName = "Weekly Vendor Report.xlsx";
SmtpClient client = new SmtpClient();
client.Host = "mail.lamrc.com";

System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
message.From = from;
message.IsBodyHtml = true;
message.Subject = strSubject;
message.Body = strBody;
message.To.Add(to);

message.Attachments.Add(new Attachment(tableStream, attchmentName, ExcelContentType));
.......

}

最佳答案

使用EPPlus用于将数据表转换为 excel 并将其转换为附件的库。

    public static Attachment GetAttachment(DataTable dataTable)
{
MemoryStream outputStream = new MemoryStream();
using (ExcelPackage package = new ExcelPackage(outputStream))
{
ExcelWorksheet facilityWorksheet = package.Workbook.Worksheets.Add("sheetName");
facilityWorksheet.Cells.LoadFromDataTable(dataTable, true);

package.Save();
}

outputStream.Position = 0;
Attachment attachment = new Attachment(outputStream, "sample.xlsx", "application/vnd.ms-excel");

retutn attachment;
}

关于c# - 在 c# 中从数据表发送带有 excel 作为附件的电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53606317/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com