我有一段代码可以从datagridview创建工作簿。单击一个按钮并且不将文件保存到磁盘后,我希望能够将该工作簿附加到Outlook中,以便我可以选择将其发送给谁。
这是我想要达到的结果:
但是,当我运行代码时,电子邮件会打开,但没有附件,只有以下错误消息:
这是我的代码:
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();
不幸的是,我得到了一个非常模糊的错误:
答案 0 :(得分:2)
我的建议是保存并关闭工作簿,并使用文件名作为附件。我测试了这个,它确实产生了你想要的结果:
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");
答案 1 :(得分:0)
复活的线程:
excel.Dialogs[Microsoft.Office.Interop.Excel.XlBuiltInDialog.xlDialogSendMail].Show();