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

我有一段代码从datagridview创build工作簿。 点击一个button后,如果不将文件保存到磁盘上,我希望能够将该工作簿附加到Outlook中,然后我可以select将其发送给哪个人。

这是我想要达到的结果:

例子1

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

例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(); 

不幸的是我得到一个非常模糊的错误:

错误的图像

我的build议是保存和closures工作簿,并使用文件名作为附件。 我testing了这一点,它确实产生了你所寻求的结果:

 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");