作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一段代码可以从数据 GridView 创建工作簿。单击按钮但未将文件保存到磁盘后,我希望能够将该工作簿附加到 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();
不幸的是,我遇到了一个非常模糊的错误:
最佳答案
我的建议是保存并关闭工作簿,并使用文件名作为附件。我对此进行了测试,它确实产生了您想要的结果:
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/
使用登录后,我想吐出用户名。 但是,当我尝试单击登录按钮时, 它给了我力量。 我看着logcat,但是什么也没显示。 这种编码是在说。 它将根据我在登录屏幕中输入的名称来烘烤用户名。 不会有任何密码。
关闭。这个问题不符合Stack Overflow guidelines .它目前不接受答案。 这个问题似乎是题外话,因为它缺乏足够的信息来诊断问题。 更详细地描述您的问题或include a min
我是一名优秀的程序员,十分优秀!