gpt4 book ai didi

C# 我想将工作簿附加到 Outlook 电子邮件并在发送前预览

转载 作者:行者123 更新时间:2023-11-30 23:19:30 24 4
gpt4 key购买 nike

我有一段代码可以从数据 GridView 创建工作簿。单击按钮但未将文件保存到磁盘后,我希望能够将该工作簿附加到 Outlook 中,这样我就可以选择将其发送给谁。

这是我想要达到的结果:

example 1

但是,当我运行代码时,电子邮件打开但没有附件,只有这个错误消息:

example 2

这是我的代码:

private void attachEmail()
{
Microsoft.Office.Interop.Excel._Application excel = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel._Workbook workbook = excel.Workbooks.Add(Type.Missing);
Microsoft.Office.Interop.Excel._Worksheet worksheet = null;
Outlook.Application outlookApp = new Outlook.Application();
Outlook.MailItem mailItem = (Outlook.MailItem)outlookApp.CreateItem(Outlook.OlItemType.olMailItem);
try
{
worksheet = workbook.ActiveSheet;
worksheet.Name = "Sheet1";
for (int i = 0; i < mydataGridView.Columns.Count; i++)
{
worksheet.Cells[1, i + 1] = mydataGridView.Columns[i].HeaderText;
}
for (int i = 0; i < mydataGridView.Rows.Count; i++)
{
for (int j = 0; j < mydataGridView.Columns.Count; j++)
{
worksheet.Cells[i + 2, j + 1] = mydataGridView.Rows[i].Cells[j].Value.ToString();
}
}
mailItem.Subject = "Notification";
mailItem.Importance = Outlook.OlImportance.olImportanceHigh;
mailItem.Display(false);
mailItem.Attachments.Add(workbook);
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
excel.Quit();
workbook = null;
excel = null;
}
}

使用代码更新进行编辑

我偶然发现了一些从内存中检索数据的代码。我不确定它是如何工作的(我是编码新手),但它正在做一些不同的事情,我想接近我想要实现的目标(这是将文件附加到 Outlook 而不先保存它) :

            MemoryStream stream = new MemoryStream();
workbook.SaveAs(stream);
Byte[] bytearray = (Byte[])Array.CreateInstance(typeof(byte), stream.Length);
stream.Position = 0;
stream.Read(bytearray, 0, (int)stream.Length);
MemoryStream ms = new MemoryStream(bytearray);
System.Net.Mail.Attachment attachment = new System.Net.Mail.Attachment(ms, "excelfile.xlsx");
mailItem.Subject = "Notification";
mailItem.Importance = Outlook.OlImportance.olImportanceHigh;
mailItem.Display(false);
mailItem.Attachments.Add(attachment);
stream.Close();

不幸的是,我遇到了一个非常模糊的错误:

Image of error

最佳答案

我的建议是保存并关闭工作簿,并使用文件名作为附件。我对此进行了测试,它确实产生了您想要的结果:

workbook.SaveAs(@"c:\cdh\foo.xlsx");
workbook.Close();

mailItem.Subject = "Notification";
mailItem.Importance = Outlook.OlImportance.olImportanceHigh;
mailItem.Display(false);
mailItem.Attachments.Add(@"c:\cdh\foo.xlsx");

关于C# 我想将工作簿附加到 Outlook 电子邮件并在发送前预览,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40226052/

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