使用Microsoft.Office.Interop.Excel

时间:2017-06-09 18:58:19

标签: c# excel email interop

我正在尝试使用

发送附带excel文件的电子邮件
using Microsoft.Office.Interop.Excel

我将我的数据表更改为excel并尝试使用该文件发送电子邮件。但他们正在给出错误。

错误:System.Runtime.InteropServices.COMException:无法访问“My_Data.xls”。

这是代码。

void SendEmail()
{
    //get the data from database
    DataTable data = GetData();

    // Create an Excel object and add workbook...
    Excel.ApplicationClass excel = new Excel.ApplicationClass();
    Excel.Workbook workbook = excel.Application.Workbooks.Add(true); 

    // Add column headings
    int iCol = 0;
    foreach (DataColumn c in data.Columns)
    {
        iCol++;
        excel.Cells[1, iCol] = c.ColumnName;
    }
    // for each row of data...
    int iRow = 0;
    foreach (DataRow r in data.Rows)
    {
        iRow++;

        // add each row's cell data...
        iCol = 0;
        foreach (DataColumn c in data.Columns)
        {
            iCol++;
            excel.Cells[iRow + 1, iCol] = r[c.ColumnName];
        }
    }

    // Global missing reference for objects we are not defining...
    object missing = System.Reflection.Missing.Value;

    // If wanting to Save the workbook...
    workbook.SaveAs("My_Data.xls",
    Excel.XlFileFormat.xlOpenXMLWorkbook, missing, missing,
        false, false, Excel.XlSaveAsAccessMode.xlNoChange,
        missing, missing, missing, missing, missing);

    String from = "aa.gmail.com";

    String to = "bb.gmail.com";

    using (MailMessage mm = new MailMessage(from, to))
    {    
        SmtpClient smtp = new SmtpClient();
        mm.Subject = "List";
        //I have no idea for this part
        mm.Attachments.Add("My_Data.xls");
        mm.IsBodyHtml = true;

        smtp.Host = "smtp.gmail.com";
        smtp.EnableSsl = true;
        System.Net.NetworkCredential credentials = new System.Net.NetworkCredential();
        credentials.UserName = "aa@gmail.com";
        credentials.Password = "1234";
        smtp.UseDefaultCredentials = true;
        smtp.Credentials = credentials;
        smtp.Port = 587;
        smtp.Send(mm);
    }
}

2 个答案:

答案 0 :(得分:0)

尝试保存工作簿,然后打开/附加:

  workbook.SaveAs(@"path\to\workbook.xlsx");
  workbook.Close();

  mailObject.Attachments.Add(@"path\to\workbook.xlsx");

答案 1 :(得分:0)

需要创建附件项目,尝试替换

mm.Attachments.Add(@"My_Data.xls");

mm.Attachments.Add(new Attachment(@"My_Data.xls"));