0

I am able to create no.of Documents according to DataSource (excel data) and would like to send same document to concerened person emailid (mentioned in excel) but I get this above error. Here is the below code i am using :

      private void GenerateMultipleDocumentAndSendEmail()
    {

        Microsoft.Office.Interop.Word.Application myWordApp = new Microsoft.Office.Interop.Word.Application(); 
        object oMissing = System.Reflection.Missing.Value; 
        object oNotTrue = false; 
        object oFilename = @"D:\Title.doc"; // word template
        myWordApp.Visible = false; 
        //Create connection object
        string constring = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + txtBrowse.Text + "; Extended Properties=Excel 12.0 Xml";
        OleDbConnection con = new OleDbConnection(constring);
        try
        {
            int iCount = 0;
            con.Open();
            dt = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
            string[] excelsheets = new string[dt.Rows.Count];
            foreach (System.Data.DataRow dr in dt.Rows)
            {
                excelsheets[iCount] = dr["TABLE_NAME"].ToString();
                iCount++;
            }
            for (int jCount = 0; jCount < excelsheets.Length; jCount++)
            {
                OleDbCommand cmd = new OleDbCommand("Select * from [" + excelsheets[jCount] + "]");
                cmd.Connection = con;
                //cmd.CommandText=CommandBindings
                try
                {
                    OleDbDataReader reader = cmd.ExecuteReader();
                    int i = 1;
                    while (reader.Read())
                    {
                        Microsoft.Office.Interop.Word.Document mydoc = myWordApp.Documents.Add();//new Microsoft.Office.Interop.Word.Document();//
                        object destination = @"D:\NewDocument" + i.ToString() + ".doc";
                        System.Collections.Generic.Dictionary<string, string> row = new System.Collections.Generic.Dictionary<string, string>();
                        row.Add("Title", reader.GetString(0).ToString());
                        row.Add("FirstName", reader.GetString(1).ToString());
                        row.Add("MiddleName", reader.GetString(2).ToString());
                        row.Add("LastName", reader.GetString(3).ToString());
                        row.Add("Suffix", reader.GetString(4).ToString());
                        row.Add("Company", reader.GetString(5).ToString());
                        row.Add("EmailAddress", reader.GetString(6).ToString());
                        mydoc = myWordApp.Documents.Add(ref oFilename, ref oMissing, ref oMissing, ref oMissing);

                        foreach (Word.MailMergeField myField in mydoc.MailMerge.Fields)
                        {
                            myField.Select();
                            string key = myWordApp.Selection.Text;
                            key = key.Replace("»", "").Replace("«", "");

                            if (row.ContainsKey(key))
                            {
                                string text = row[key];
                                myWordApp.Selection.TypeText(text);
                            }
                        }

                        mydoc.SaveAs(ref destination, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
                        mydoc.Close(ref oNotTrue, ref oMissing, ref oMissing);
                       //mydoc = myWordApp.Documents.Open(ref destination, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
                        myWordApp.ActiveDocument.MailMerge.Destination = Word.WdMailMergeDestination.wdSendToEmail; //am getting error at this line as Requested object is not available.
                      //  mydoc.MailMerge.MailFormat = Word.WdMailMergeMailFormat.wdMailFormatPlainText;
                        myWordApp.ActiveDocument.MailMerge.MailAsAttachment = false;
                        myWordApp.ActiveDocument.MailMerge.MailSubject = "Hi welcome to Test1";
                        myWordApp.ActiveDocument.MailMerge.MailAddressFieldName = "EmailAddress";
                        myWordApp.ActiveDocument.MailMerge.Execute(ref oNotTrue);



                        i++;
                    }//end while
                    //reader.Close();
                }//try end
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                finally
                {
                    cmd.Dispose();
                    con.Close();
                    con.Dispose();
                    myWordApp.Application.Quit(ref oNotTrue, ref oMissing, ref oMissing);
                }
            }
        }



        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

    }

Title.doc is my template and am using excel as datasource.I am trying to send email to mailmerge doc to emailid mentioned in excelsheet.

5
  • 1
    I suppose that you are opening a document without any MailMerge fields defined
    – Steve
    Aug 1, 2013 at 7:45
  • I want to send saved NewDocument1.doc to corresponding email addressin excel.Couldn't get it how can i define MailMerge fields.Could you please suggest me how can i define
    – kida
    Aug 1, 2013 at 7:56
  • The usual steps are: Create a document template with word inserting text and MergeField with the usual tools (Insert -> Fields -> MergeField -> give a name -> OK). When finished save this template in a know folder for your application. In code open this file and SaveAs it with the final name, apply the code to substitute the MergeFields and then save again. Repeat for every row. If you want just one doc, then you need to study how to copy/paste block of texts from the original template to the final document. As you can see it is a bit of work, but not rocket science.
    – Steve
    Aug 1, 2013 at 8:04
  • I tired what ever you said but my pC hangs at OpenDataSource() changed subtype,sqlstatement and done by doing all options as missing except the fielpath.Nothing worked ...any idea?
    – kida
    Aug 1, 2013 at 10:07
  • 1
    Late comment but (a) I guess you removed the OpenDataSource from your code. (b) for Word/Excel 2010/2013 (and possibly 2007) it should be enough to provide the path+file name of the workbook, and a SQLStatement such as "SELECT * FROM [Sheet1$]" where Sheet1 is the name of the sheet. You should not need a connection string or a subtype. (c) if you already have the workbook open via an OleDbConnection when you use OpenDataSource, I would guess that Word would fail to connect (I haven't checked).
    – user1379931
    Sep 5, 2013 at 12:01

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.