App使用word interop时崩溃

时间:2016-06-18 22:23:31

标签: c# ms-word interop

当我尝试在Win 8上导出.doc文件时,应用程序崩溃并返回此错误,此外,它会打开2个savedialogs预期的一个,另一个使用源.doc文件的名称保存为副本

这是错误:

System.Runtime.InteropServices.COMException (0x800A1066): O comando falhou
   em Microsoft.Office.Interop.Word.DocumentClass.SaveAs(Object& FileName, Object& FileFormat, Object& LockComments, Object& Password, Object& AddToRecentFiles, Object& WritePassword, Object& ReadOnlyRecommended, Object& EmbedTrueTypeFonts, Object& SaveNativePictureFormat, Object& SaveFormsData, Object& SaveAsAOCELetter, Object& Encoding, Object& InsertLineBreaks, Object& AllowSubstitutions, Object& LineEnding, Object& AddBiDiMarks)
   em cadastramento.funcionarios.CreateWordDocument(Object fileName, Object saveAs) na C:\Users\Blind\Desktop\projeto\01cadastramento atual\cadastramento\funcionarios.cs:linha 949
   em cadastramento.funcionarios.button9_Click(Object sender, EventArgs e) na C:\Users\Blind\Desktop\projeto\01cadastramento atual\cadastramento\funcionarios.cs:linha 523
   em System.Windows.Forms.Control.OnClick(EventArgs e)
   em System.Windows.Forms.Button.OnClick(EventArgs e)
   em System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
   em System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
   em System.Windows.Forms.Control.WndProc(Message& m)
   em System.Windows.Forms.ButtonBase.WndProc(Message& m)
   em System.Windows.Forms.Button.WndProc(Message& m)
   em System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
   em System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
   em System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)

引用的行是:

          CreateWordDocument(caminho, "");    //523

  aDoc.SaveAs(ref saveAs, ref missing, ref missing, ref missing,
                            ref missing, ref missing, ref missing, ref missing,
                            ref missing, ref missing, ref missing, ref missing,
                            ref missing, ref missing, ref missing, ref missing); //949

表单字部分代码,是从各种来源实现的,我一直试着把它弄好,所以我不知道它为什么会给出这个错误信息。

它应该起作用的预期方式是复制源文件并保存一个新文本并替换所有文本并使用savedialog。

在Win 7上似乎一切正常。

    private void button9_Click(object sender, EventArgs e)
    {
        var AssemblyPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
        var caminho = "" + AssemblyPath + "\\Resources\\FICHAREG.doc";

        CreateWordDocument(caminho, "");
    }

    private void CreateWordDocument(object fileName,
        object saveAs)
    {
        if (dataGridView1.Rows.Count != 0 && dataGridView1.Rows != null)
        {

            DataGridViewRow row = dataGridView1.SelectedRows[0];
            string vIDg = (row.Cells[0].Value.ToString());
            DataGridViewRow row2 = dataGridView1.SelectedRows[0];
            string vIDg2 = (row.Cells[1].Value.ToString());



        //Set Missing Value parameter - used to represent
        // a missing value when calling methods through
        // interop.
        object missing = System.Reflection.Missing.Value;

        //Setup the Word.Application class.
        Word.Application wordApp =
            new Word.Application();

        //Setup our Word.Document class we'll use.
        Word.Document aDoc = null;

        // Check to see that file exists
        if (File.Exists((string)fileName))
        {
            DateTime today = DateTime.Now;

            object readOnly = false;
            object isVisible = false;

            //Set Word to be not visible.
            wordApp.Visible = false;

            //Open the word document
            aDoc = wordApp.Documents.Open(ref fileName, ref missing,
                ref readOnly, ref missing, ref missing, ref missing,
                ref missing, ref missing, ref missing, ref missing,
                ref missing, ref isVisible, ref missing, ref missing,
                ref missing, ref missing);






            // Activate the document
            aDoc.Activate();

            // Find Place Holders and Replace them with Values.



            string constring = @"Data Source=|DataDirectory|\cadastramentodb.sdf;Persist Security Info=False";
            string Query = "SELECT * FROM Funcionarios WHERE (id = @id)";
            SqlCeConnection conDataBase = new SqlCeConnection(constring);
            SqlCeCommand cmdDataBase = new SqlCeCommand(Query, conDataBase);
            cmdDataBase.Parameters.Add("@id", SqlDbType.NVarChar).Value = vIDg;
            SqlCeDataReader myReader;
            try
            {
                conDataBase.Open();
                myReader = cmdDataBase.ExecuteReader();

                while (myReader.Read())
                {

                    string nomefuncs = myReader.GetString(1);
                    var nomefunc = nomefuncs.ToString();
                    this.FindAndReplace(wordApp, "$$nomefunc$$", "" + nomefunc + "");

                    string numordems = myReader.GetString(82);
                    var numordem = numordems.ToString();
                    this.FindAndReplace(wordApp, "$$numordem$$", "" + numordem + "");

                    string nummatriculas = myReader.GetString(83);
                    var nummatricula = nummatriculas.ToString();
                    this.FindAndReplace(wordApp, "$$nummatricula$$", "" + nummatricula + "");

                    string nomepaifuncs = myReader.GetString(2);
                    var nomepaifunc = nomepaifuncs.ToString();
                    this.FindAndReplace(wordApp, "$$nomepaifunc$$", "" + nomepaifunc + "");

                    string nomemaefuncs = myReader.GetString(3);
                    var nomemaefunc = nomemaefuncs.ToString();
                    this.FindAndReplace(wordApp, "$$nomemaefunc$$", "" + nomemaefunc + "");

                    string paifuncnacios = myReader.GetString(4);
                    var paifuncnacio = paifuncnacios.ToString();
                    this.FindAndReplace(wordApp, "$$paifuncnacio$$", "" + paifuncnacio + "");

                    string maefuncnacios = myReader.GetString(5);
                    var maefuncnacio = maefuncnacios.ToString();
                    this.FindAndReplace(wordApp, "$$maefuncnacio$$", "" + maefuncnacio + "");

                    DateTime datanascs = myReader.GetDateTime(6);
                    var datanasc = datanascs.ToShortDateString();
                    this.FindAndReplace(wordApp, "$$datanasc$$", "" + datanasc + "");

                    string idades = myReader.GetString(88);
                    var idade = idades.ToString();
                    this.FindAndReplace(wordApp, "$$idade$$", "" + idade + "");

                    string funcnacios = myReader.GetString(7);
                    var funcnacio = funcnacios.ToString();
                    this.FindAndReplace(wordApp, "$$funcnacio$$", "" + funcnacio + "");

                    string estadocivils = myReader.GetString(8);
                    var estadocivil = estadocivils.ToString();
                    this.FindAndReplace(wordApp, "$$estadocivil$$", "" + estadocivil + "");

                    string localnascs = myReader.GetString(9);
                    var localnasc = localnascs.ToString();
                    this.FindAndReplace(wordApp, "$$localnasc$$", "" + localnasc + "");

                    string ufnascs = myReader.GetString(10);
                    var ufnasc = ufnascs.ToString();
                    this.FindAndReplace(wordApp, "$$ufnasc$$", "" + ufnasc + "");

                    string rgs = myReader.GetString(11);
                    var rg = rgs.ToString();
                    this.FindAndReplace(wordApp, "$$rg$$", "" + rg + "");

                    string ctpssa = myReader.GetString(12);
                    var ctps = ctpssa.ToString();
                    this.FindAndReplace(wordApp, "$$ctps$$", "" + ctps + "");

                    string ctpsss = myReader.GetString(13);
                    var ctpss = ctpsss.ToString();
                    this.FindAndReplace(wordApp, "$$ctpss$$", "" + ctpss + "");

                    string reservistas = myReader.GetString(14);
                    var reservista = reservistas.ToString();
                    this.FindAndReplace(wordApp, "$$reservista$$", "" + reservista + "");

                    string catreservistas = myReader.GetString(15);
                    var catreservista = catreservistas.ToString();
                    this.FindAndReplace(wordApp, "$$catreservista$$", "" + catreservista + "");

                    string cpfs = myReader.GetString(16);
                    var cpf = cpfs.ToString();
                    this.FindAndReplace(wordApp, "$$cpf$$", "" + cpf + "");

                    string tituloeleitors = myReader.GetString(17);
                    var tituloeleitor = tituloeleitors.ToString();
                    this.FindAndReplace(wordApp, "$$tituloeleitor$$", "" + tituloeleitor + "");

                    string carteirasaudes = myReader.GetString(18);
                    var carteirasaude = carteirasaudes.ToString();
                    this.FindAndReplace(wordApp, "$$carteirasaude$$", "" + carteirasaude + "");

                    string cbos = myReader.GetString(19);
                    var cbo = cbos.ToString();
                    this.FindAndReplace(wordApp, "$$cbo$$", "" + cbo + "");

                    string cartmod19s = myReader.GetString(20);
                    var cartmod19 = cartmod19s.ToString();
                    this.FindAndReplace(wordApp, "$$cartmod19$$", "" + cartmod19 + "");

                    string casadobrasileiros = myReader.GetString(21);
                    var casadobrasileiro = casadobrasileiros.ToString();
                    this.FindAndReplace(wordApp, "$$casadobrasileiro$$", "" + casadobrasileiro + "");

                    string naturalizados = myReader.GetString(22);
                    var naturalizado = naturalizados.ToString();
                    this.FindAndReplace(wordApp, "$$naturalizado$$", "" + naturalizado + "");

                    string filhosbrasileiross = myReader.GetString(23);
                    var filhosbrasileiros = filhosbrasileiross.ToString();
                    this.FindAndReplace(wordApp, "$$filhosbrasileiros$$", "" + filhosbrasileiros + "");

                    string datachegadabrasils = myReader.GetString(25);
                    var datachegadabrasil = datachegadabrasils.ToString();
                    this.FindAndReplace(wordApp, "$$datachegadabrasil$$", "" + datachegadabrasil + "");

                    string nregistrogerals = myReader.GetString(26);
                    var nregistrogeral = nregistrogerals.ToString();
                    this.FindAndReplace(wordApp, "$$nregistrogeral$$", "" + nregistrogeral + "");

                    string nomeconjuges = myReader.GetString(27);
                    var nomeconjuge = nomeconjuges.ToString();
                    this.FindAndReplace(wordApp, "$$nomeconjuge$$", "" + nomeconjuge + "");

                    string quantosfilhoss = myReader.GetString(24);
                    var quantosfilhos = quantosfilhoss.ToString();
                    this.FindAndReplace(wordApp, "$$quantosfilhos$$", "" + quantosfilhos + "");

                    string enderecos = myReader.GetString(28);
                    var endereco = enderecos.ToString();
                    this.FindAndReplace(wordApp, "$$endereco$$", "" + endereco + "");

                    string mudancaenderecos = myReader.GetString(29);
                    var mudancaendereco = nregistrogerals.ToString();
                    this.FindAndReplace(wordApp, "$$mudancaendereco$$", "" + mudancaendereco + "");

                    string corfuncs = myReader.GetString(70);
                    var corfunc = corfuncs.ToString();
                    this.FindAndReplace(wordApp, "$$corfunc$$", "" + corfunc + "");

                    string alturafuncs = myReader.GetString(71);
                    var alturafunc = alturafuncs.ToString();
                    this.FindAndReplace(wordApp, "$$alturafunc$$", "" + alturafunc + "");


                    string pesofuncs = myReader.GetString(72);
                    var pesofunc = pesofuncs.ToString();
                    this.FindAndReplace(wordApp, "$$pesofunc$$", "" + pesofunc + "");

                    string cabelosfuncs = myReader.GetString(73);
                    var cabelofunc = cabelosfuncs.ToString();
                    this.FindAndReplace(wordApp, "$$cabelosfunc$$", "" + cabelofunc + "");

                    string olhosfuncs = myReader.GetString(74);
                    var olhosfunc = olhosfuncs.ToString();
                    this.FindAndReplace(wordApp, "$$olhosfunc$$", "" + olhosfunc + "");

                    string sinaisfuncs = myReader.GetString(75);
                    var sinaisfunc = sinaisfuncs.ToString();
                    this.FindAndReplace(wordApp, "$$sinaisfunc$$", "" + sinaisfunc + "");


                    string dependente1s = myReader.GetString(30);
                    var dependente1 = dependente1s.ToString();
                    this.FindAndReplace(wordApp, "$$dependente1$$", "" + dependente1 + "");

                    string dependente2s = myReader.GetString(33);
                    var dependente2 = dependente2s.ToString();
                    this.FindAndReplace(wordApp, "$$dependente2$$", "" + dependente2 + "");

                    string dependente3s = myReader.GetString(36);
                    var dependente3 = dependente3s.ToString();
                    this.FindAndReplace(wordApp, "$$dependente3$$", "" + dependente3 + "");

                    string dependente4s = myReader.GetString(39);
                    var dependente4 = dependente4s.ToString();
                    this.FindAndReplace(wordApp, "$$dependente4$$", "" + dependente4 + "");

                    string dependente5s = myReader.GetString(42);
                    var dependente5 = dependente5s.ToString();
                    this.FindAndReplace(wordApp, "$$dependente5$$", "" + dependente5 + "");


                    string dependente6s = myReader.GetString(45);
                    var dependente6 = dependente6s.ToString();
                    this.FindAndReplace(wordApp, "$$dependente6$$", "" + dependente6 + "");

                    string dependente1parentes = myReader.GetString(31);
                    var depentende1parente = dependente1parentes.ToString();
                    this.FindAndReplace(wordApp, "$$dependente1parente$$", "" + depentende1parente + "");

                    string dependente2parentes = myReader.GetString(34);
                    var dependente2parente = dependente2parentes.ToString();
                    this.FindAndReplace(wordApp, "$$dependente2parente$$", "" + dependente2parente + "");

                    string dependente3parentes = myReader.GetString(37);
                    var dependente3parente = dependente3parentes.ToString();
                    this.FindAndReplace(wordApp, "$$dependente3parente$$", "" + dependente3parente + "");

                    string dependente4parentes = myReader.GetString(40);
                    var dependente4parente = dependente4parentes.ToString();
                    this.FindAndReplace(wordApp, "$$dependente4parente$$", "" + dependente4parente + "");

                    string dependente5parentes = myReader.GetString(43);
                    var dependente5parente = dependente5parentes.ToString();
                    this.FindAndReplace(wordApp, "$$dependente5parente$$", "" + dependente5parente + "");

                    string dependente6parentes = myReader.GetString(46);
                    var dependente6parente = dependente6parentes.ToString();
                    this.FindAndReplace(wordApp, "$$dependente6parente$$", "" + dependente6parente + "");

                    string dependente1nascs = myReader.GetString(32);
                    var dependente1nasc = dependente1nascs.ToString();
                    this.FindAndReplace(wordApp, "$$dependente1nasc$$", "" + dependente1nasc + "");

                    string dependente2nascs = myReader.GetString(35);
                    var dependente2nasc = dependente2nascs.ToString();
                    this.FindAndReplace(wordApp, "$$dependente2nasc$$", "" + dependente2nasc + "");

                    string dependente3nascs = myReader.GetString(38);
                    var dependente3nasc = dependente3nascs.ToString();
                    this.FindAndReplace(wordApp, "$$dependente3nasc$$", "" + dependente3nasc + "");

                    string dependente4nascs = myReader.GetString(41);
                    var dependente4nasc = dependente4nascs.ToString();
                    this.FindAndReplace(wordApp, "$$dependente4nasc$$", "" + dependente4nasc + "");

                    string dependente5nascs = myReader.GetString(44);
                    var dependente5nasc = dependente5nascs.ToString();
                    this.FindAndReplace(wordApp, "$$dependente5nasc$$", "" + dependente5nasc + "");

                    string dependente6nascs = myReader.GetString(47);
                    var dependente6nasc = dependente6nascs.ToString();
                    this.FindAndReplace(wordApp, "$$dependente6nasc$$", "" + dependente6nasc + "");

                    string datacadpiss = myReader.GetString(48);
                    var datacadpis = datacadpiss.ToString();
                    this.FindAndReplace(wordApp, "$$datacadpis$$", "" + datacadpis + "");

                    string piss = myReader.GetString(49);
                    var pis = piss.ToString();
                    this.FindAndReplace(wordApp, "$$pis$$", "" + pis + "");

                    string nobancopiss = myReader.GetString(50);
                    var nobancopis = nobancopiss.ToString();
                    this.FindAndReplace(wordApp, "$$nobancopis$$", "" + nobancopis + "");

                    string endpiss = myReader.GetString(51);
                    var endpis = endpiss.ToString();
                    this.FindAndReplace(wordApp, "$$endpis$$", "" + endpis + "");

                    string bancopiss = myReader.GetString(52);
                    var bancopis = bancopiss.ToString();
                    this.FindAndReplace(wordApp, "$$bancopis$$", "" + bancopis + "");

                    string agpiss = myReader.GetString(53);
                    var agpis = agpiss.ToString();
                    this.FindAndReplace(wordApp, "$$agpis$$", "" + agpis + "");

                    DateTime dataentradas = myReader.GetDateTime(54);
                    var dataentrada = dataentradas.ToShortDateString();
                    this.FindAndReplace(wordApp, "$$dataentrada$$", "" + dataentrada + "");

                    DateTime dataregs = myReader.GetDateTime(55);
                    var datareg = dataregs.ToShortDateString();
                    this.FindAndReplace(wordApp, "$$datareg$$", "" + datareg + "");

                    string ocupacaos = myReader.GetString(56);
                    var ocupacao = ocupacaos.ToString();
                    this.FindAndReplace(wordApp, "$$ocupacao$$", "" + ocupacao + "");

                    string secaos = myReader.GetString(57);
                    var secao = secaos.ToString();
                    this.FindAndReplace(wordApp, "$$secao$$", "" + secao + "");

                    string salarioinicials = myReader.GetString(58);
                    var salarioinicial = salarioinicials.ToString();
                    this.FindAndReplace(wordApp, "$$salarioinicial$$", "" + salarioinicial + "");

                    string comissoess = myReader.GetString(59);
                    var comissoes = comissoess.ToString();
                    this.FindAndReplace(wordApp, "$$comissoes$$", "" + comissoes + "");

                    string tarefas = myReader.GetString(60);
                    var tarefa = tarefas.ToString();
                    this.FindAndReplace(wordApp, "$$tarefa$$", "" + tarefa + "");

                    string formapagamentos = myReader.GetString(61);
                    var formapagamento = formapagamentos.ToString();
                    this.FindAndReplace(wordApp, "$$formapagamento$$", "" + formapagamento + "");

                    string eoptantes = myReader.GetString(62);
                    var eoptante = eoptantes.ToString();
                    this.FindAndReplace(wordApp, "$$eoptante$$", "" + eoptante + "");

                    DateTime dataopcaos = myReader.GetDateTime(63);
                    var dataopcao = dataopcaos.ToShortDateString();
                    this.FindAndReplace(wordApp, "$$dataopcao$$", "" + dataopcao + "");

                    DateTime dataretratacaos = myReader.GetDateTime(64);
                    var dataretratacao = dataretratacaos.ToShortDateString();
                    this.FindAndReplace(wordApp, "$$dataretratacao$$", "" + dataretratacao + "");

                    string bancodepositarios = myReader.GetString(69);
                    var bancodepositario = bancodepositarios.ToString();
                    this.FindAndReplace(wordApp, "$$bancodepositario$$", "" + bancodepositario + "");

                    string hentradas = myReader.GetString(65);
                    var hentrada = hentradas.ToString();
                    this.FindAndReplace(wordApp, "$$hentrada$$", "" + hentrada + "");


                    string halmocos = myReader.GetString(66);
                    var halmoco = halmocos.ToString();
                    this.FindAndReplace(wordApp, "$$halmoco$$", "" + halmoco + "");


                    string hsaidas = myReader.GetString(67);
                    var hsaida = hsaidas.ToString();
                    this.FindAndReplace(wordApp, "$$hsaida$$", "" + hsaida + "");


                    string dsrs = myReader.GetString(68);
                    var dsr = dsrs.ToString();
                    this.FindAndReplace(wordApp, "$$dsr$$", "" + dsr + "");


                }

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







        }
        else
        {
            MessageBox.Show("Arquivo faltando.");
            return;
        }


        SaveFileDialog saveFileDialog1 = new SaveFileDialog();
        saveFileDialog1.Filter = "Documento do Word|*.doc";
        saveFileDialog1.Title = "Salvar";
        saveFileDialog1.FileName = "FICHA DE REGISTRO "+ vIDg2 +"";
        if (DialogResult.OK == saveFileDialog1.ShowDialog())
        {
            string docName = saveFileDialog1.FileName;
            if (docName.Length > 0)
            {


                saveAs = (object)docName;
                //Save the document as the correct file name.
                aDoc.SaveAs(ref saveAs, ref missing, ref missing, ref missing,
                        ref missing, ref missing, ref missing, ref missing,
                        ref missing, ref missing, ref missing, ref missing,
                        ref missing, ref missing, ref missing, ref missing);





            }
        }


        //Close the document - you have to do this.
        ((Microsoft.Office.Interop.Word._Document)aDoc).Close(ref missing, ref missing, ref missing);

        MessageBox.Show("File created.");

    }

    ///////////////////////////////////////////////

        else
        {
            MessageBox.Show("Não há elementos para editar.", "Não há elementos para editar", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);

            this.funcionariosTableAdapter.Fill(this.cadastramentodbDataSet.Funcionarios);

            string constringF = @"Data Source=|DataDirectory|\cadastramentodb.sdf;Persist Security Info=False";
            string QueryF = "SELECT * FROM Funcionarios WHERE (status = @status and  idsetor = @idsetor and idempresa = @idempresa) ";

            SqlCeConnection conDataBaseF = new SqlCeConnection(constringF);
            SqlCeCommand cmdDataBaseF = new SqlCeCommand(QueryF, conDataBaseF);
            cmdDataBaseF.Parameters.Add("@status", SqlDbType.NVarChar).Value = comboBox1.Text;
            cmdDataBaseF.Parameters.Add("@idsetor", SqlDbType.NVarChar).Value = comboBox3.Text;
            cmdDataBaseF.Parameters.Add("@idempresa", SqlDbType.NVarChar).Value = comboBox2.Text;
            try
            {


                SqlCeDataAdapter sda = new SqlCeDataAdapter();
                sda.SelectCommand = cmdDataBaseF;


                System.Data.DataTable dbdatasetF = new System.Data.DataTable();
                sda.Fill(dbdatasetF);
                BindingSource bSourceF = new BindingSource();

                bSourceF.DataSource = dbdatasetF;
                dataGridView1.DataSource = bSourceF;
                sda.Update(dbdatasetF);
            }

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



        }




    }

    /// <summary>
    /// This is simply a helper method to find/replace 
    /// text.
    /// </summary>
    /// <param name="WordApp">Word Application to use</param>
    /// <param name="findText">Text to find</param>
    /// <param name="replaceWithText">Replacement text</param>
    private void FindAndReplace(Word.Application WordApp,
                                object findText,
                                object replaceWithText)
    {
        object matchCase = true;
        object matchWholeWord = true;
        object matchWildCards = false;
        object matchSoundsLike = false;
        object nmatchAllWordForms = false;
        object forward = true;
        object format = false;
        object matchKashida = false;
        object matchDiacritics = false;
        object matchAlefHamza = false;
        object matchControl = false;
        object read_only = false;
        object visible = true;
        object replace = 2;
        object wrap = 1;

        WordApp.Selection.Find.Execute(ref findText,
            ref matchCase, ref matchWholeWord,
            ref matchWildCards, ref matchSoundsLike,
            ref nmatchAllWordForms, ref forward,
            ref wrap, ref format, ref replaceWithText,
            ref replace, ref matchKashida,
            ref matchDiacritics, ref matchAlefHamza,
            ref matchControl);
    }

1 个答案:

答案 0 :(得分:0)

(代表OP发布)

我在使用wholde Word Interop时遇到了太多麻烦,所以我转到了DocX,它运行得越来越好。

我发布了代码,所以有兴趣的人都可以访问它。比Office Interop简单得多。

 private void button9_Click(object sender, EventArgs e)
        {
            if (dataGridView1.Rows.Count != 0 && dataGridView1.Rows != null)
            {        

                        Createe();              
        }

    ///////////////////////////////////////////////

        else
        {
            MessageBox.Show("Não há elementos para gerar a ficha de registro.", "Aviso", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);

            this.funcionariosTableAdapter.Fill(this.cadastramentodbDataSet.Funcionarios);

            string constringF = @"Data Source=|DataDirectory|\cadastramentodb.sdf;Persist Security Info=False";
            string QueryF = "SELECT * FROM Funcionarios WHERE (status = @status and  idsetor = @idsetor and idempresa = @idempresa) ";

            SqlCeConnection conDataBaseF = new SqlCeConnection(constringF);
            SqlCeCommand cmdDataBaseF = new SqlCeCommand(QueryF, conDataBaseF);
            cmdDataBaseF.Parameters.Add("@status", SqlDbType.NVarChar).Value = comboBox1.Text;
            cmdDataBaseF.Parameters.Add("@idsetor", SqlDbType.NVarChar).Value = comboBox3.Text;
            cmdDataBaseF.Parameters.Add("@idempresa", SqlDbType.NVarChar).Value = comboBox2.Text;
            try
            {


                SqlCeDataAdapter sda = new SqlCeDataAdapter();
                sda.SelectCommand = cmdDataBaseF;


                System.Data.DataTable dbdatasetF = new System.Data.DataTable();
                sda.Fill(dbdatasetF);
                BindingSource bSourceF = new BindingSource();

                bSourceF.DataSource = dbdatasetF;
                dataGridView1.DataSource = bSourceF;
                sda.Update(dbdatasetF);
            }

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



        }
    }


    public void Createe()
    {
        DataGridViewRow row = dataGridView1.SelectedRows[0];
        string vIDg = (row.Cells[0].Value.ToString());
        DataGridViewRow row2 = dataGridView1.SelectedRows[0];
        string vIDg2 = (row.Cells[1].Value.ToString());

        SaveFileDialog saveFileDialog1 = new SaveFileDialog();
        saveFileDialog1.Filter = "Documento do Word|*.docx";
        saveFileDialog1.Title = "Salvar";
        saveFileDialog1.FileName = "FICHA DE REGISTRO " + vIDg2 + "";
        if (DialogResult.OK == saveFileDialog1.ShowDialog())
        {
            string OutputFile = saveFileDialog1.FileName;



            if (OutputFile.Length > 0)
            {

                var AssemblyPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
                var caminho = "" + AssemblyPath + "\\Resources\\FICHAREG2.docx";

                using (DocX document = DocX.Load(caminho))
                {
                    // Replace text in this document.

                    string constring = @"Data Source=|DataDirectory|\cadastramentodb.sdf;Persist Security Info=False";
                    string Query = "SELECT * FROM Funcionarios WHERE (id = @id)";
                    SqlCeConnection conDataBase = new SqlCeConnection(constring);
                    SqlCeCommand cmdDataBase = new SqlCeCommand(Query, conDataBase);
                    cmdDataBase.Parameters.Add("@id", SqlDbType.NVarChar).Value = vIDg;
                    SqlCeDataReader myReader;
                    try
                    {
                        conDataBase.Open();
                        myReader = cmdDataBase.ExecuteReader();

                        while (myReader.Read())
                        {

                            string nomefuncs = myReader.GetString(1);
                            var nomefunc = nomefuncs.ToString();
                            document.ReplaceText("$$nomefunc$$", "" + nomefunc + "");

                            string numordems = myReader.GetString(82);
                            var numordem = numordems.ToString();
                            document.ReplaceText("$$numordem$$", "" + numordem + "");

                            string nummatriculas = myReader.GetString(83);
                            var nummatricula = nummatriculas.ToString();
                            document.ReplaceText("$$nummatricula$$", "" + nummatricula + "");

                            string nomepaifuncs = myReader.GetString(2);
                            var nomepaifunc = nomepaifuncs.ToString();
                            document.ReplaceText("$$nomepaifunc$$", "" + nomepaifunc + "");

                            string nomemaefuncs = myReader.GetString(3);
                            var nomemaefunc = nomemaefuncs.ToString();
                            document.ReplaceText("$$nomemaefunc$$", "" + nomemaefunc + "");

                            string paifuncnacios = myReader.GetString(4);
                            var paifuncnacio = paifuncnacios.ToString();
                            document.ReplaceText("$$paifuncnacio$$", "" + paifuncnacio + "");

                            string maefuncnacios = myReader.GetString(5);
                            var maefuncnacio = maefuncnacios.ToString();
                            document.ReplaceText("$$maefuncnacio$$", "" + maefuncnacio + "");

                            DateTime datanascs = myReader.GetDateTime(6);
                            var datanasc = datanascs.ToShortDateString();
                            document.ReplaceText("$$datanasc$$", "" + datanasc + "");

                            string idades = myReader.GetString(88);
                            var idade = idades.ToString();
                            document.ReplaceText("$$idade$$", "" + idade + "");

                            string funcnacios = myReader.GetString(7);
                            var funcnacio = funcnacios.ToString();
                            document.ReplaceText("$$funcnacio$$", "" + funcnacio + "");

                            string estadocivils = myReader.GetString(8);
                            var estadocivil = estadocivils.ToString();
                            document.ReplaceText("$$estadocivil$$", "" + estadocivil + "");

                            string localnascs = myReader.GetString(9);
                            var localnasc = localnascs.ToString();
                            document.ReplaceText("$$localnasc$$", "" + localnasc + "");

                            string ufnascs = myReader.GetString(10);
                            var ufnasc = ufnascs.ToString();
                            document.ReplaceText("$$ufnasc$$", "" + ufnasc + "");

                            string rgs = myReader.GetString(11);
                            var rg = rgs.ToString();
                            document.ReplaceText("$$rg$$", "" + rg + "");

                            string ctpssa = myReader.GetString(12);
                            var ctps = ctpssa.ToString();
                            document.ReplaceText("$$ctps$$", "" + ctps + "");

                            string ctpsss = myReader.GetString(13);
                            var ctpss = ctpsss.ToString();
                            document.ReplaceText("$$ctpss$$", "" + ctpss + "");

                            string reservistas = myReader.GetString(14);
                            var reservista = reservistas.ToString();
                            document.ReplaceText("$$reservista$$", "" + reservista + "");

                            string catreservistas = myReader.GetString(15);
                            var catreservista = catreservistas.ToString();
                            document.ReplaceText("$$catreservista$$", "" + catreservista + "");

                            string cpfs = myReader.GetString(16);
                            var cpf = cpfs.ToString();
                            document.ReplaceText("$$cpf$$", "" + cpf + "");

                            string tituloeleitors = myReader.GetString(17);
                            var tituloeleitor = tituloeleitors.ToString();
                            document.ReplaceText("$$tituloeleitor$$", "" + tituloeleitor + "");

                            string carteirasaudes = myReader.GetString(18);
                            var carteirasaude = carteirasaudes.ToString();
                            document.ReplaceText("$$carteirasaude$$", "" + carteirasaude + "");

                            string cbos = myReader.GetString(19);
                            var cbo = cbos.ToString();
                            document.ReplaceText("$$cbo$$", "" + cbo + "");

                            string cartmod19s = myReader.GetString(20);
                            var cartmod19 = cartmod19s.ToString();
                            document.ReplaceText("$$cartmod19$$", "" + cartmod19 + "");

                            string casadobrasileiros = myReader.GetString(21);
                            var casadobrasileiro = casadobrasileiros.ToString();
                            document.ReplaceText("$$casadobrasileiro$$", "" + casadobrasileiro + "");

                            string naturalizados = myReader.GetString(22);
                            var naturalizado = naturalizados.ToString();
                            document.ReplaceText("$$naturalizado$$", "" + naturalizado + "");

                            string filhosbrasileiross = myReader.GetString(23);
                            var filhosbrasileiros = filhosbrasileiross.ToString();
                            document.ReplaceText("$$filhosbrasileiros$$", "" + filhosbrasileiros + "");

                            string datachegadabrasils = myReader.GetString(25);
                            var datachegadabrasil = datachegadabrasils.ToString();
                            document.ReplaceText("$$datachegadabrasil$$", "" + datachegadabrasil + "");

                            string nregistrogerals = myReader.GetString(26);
                            var nregistrogeral = nregistrogerals.ToString();
                            document.ReplaceText("$$nregistrogeral$$", "" + nregistrogeral + "");

                            string nomeconjuges = myReader.GetString(27);
                            var nomeconjuge = nomeconjuges.ToString();
                            document.ReplaceText("$$nomeconjuge$$", "" + nomeconjuge + "");

                            string quantosfilhoss = myReader.GetString(24);
                            var quantosfilhos = quantosfilhoss.ToString();
                            document.ReplaceText("$$quantosfilhos$$", "" + quantosfilhos + "");

                            string enderecos = myReader.GetString(28);
                            var endereco = enderecos.ToString();
                            document.ReplaceText("$$endereco$$", "" + endereco + "");

                            string mudancaenderecos = myReader.GetString(29);
                            var mudancaendereco = nregistrogerals.ToString();
                            document.ReplaceText("$$mudancaendereco$$", "" + mudancaendereco + "");

                            string corfuncs = myReader.GetString(70);
                            var corfunc = corfuncs.ToString();
                            document.ReplaceText("$$corfunc$$", "" + corfunc + "");

                            string alturafuncs = myReader.GetString(71);
                            var alturafunc = alturafuncs.ToString();
                            document.ReplaceText("$$alturafunc$$", "" + alturafunc + "");


                            string pesofuncs = myReader.GetString(72);
                            var pesofunc = pesofuncs.ToString();
                            document.ReplaceText("$$pesofunc$$", "" + pesofunc + "");

                            string cabelosfuncs = myReader.GetString(73);
                            var cabelofunc = cabelosfuncs.ToString();
                            document.ReplaceText("$$cabelosfunc$$", "" + cabelofunc + "");

                            string olhosfuncs = myReader.GetString(74);
                            var olhosfunc = olhosfuncs.ToString();
                            document.ReplaceText("$$olhosfunc$$", "" + olhosfunc + "");

                            string sinaisfuncs = myReader.GetString(75);
                            var sinaisfunc = sinaisfuncs.ToString();
                            document.ReplaceText("$$sinaisfunc$$", "" + sinaisfunc + "");


                            string dependente1s = myReader.GetString(30);
                            var dependente1 = dependente1s.ToString();
                            document.ReplaceText("$$dependente1$$", "" + dependente1 + "");

                            string dependente2s = myReader.GetString(33);
                            var dependente2 = dependente2s.ToString();
                            document.ReplaceText("$$dependente2$$", "" + dependente2 + "");

                            string dependente3s = myReader.GetString(36);
                            var dependente3 = dependente3s.ToString();
                            document.ReplaceText("$$dependente3$$", "" + dependente3 + "");

                            string dependente4s = myReader.GetString(39);
                            var dependente4 = dependente4s.ToString();
                            document.ReplaceText("$$dependente4$$", "" + dependente4 + "");

                            string dependente5s = myReader.GetString(42);
                            var dependente5 = dependente5s.ToString();
                            document.ReplaceText("$$dependente5$$", "" + dependente5 + "");


                            string dependente6s = myReader.GetString(45);
                            var dependente6 = dependente6s.ToString();
                            document.ReplaceText("$$dependente6$$", "" + dependente6 + "");

                            string dependente1parentes = myReader.GetString(31);
                            var depentende1parente = dependente1parentes.ToString();
                            document.ReplaceText("$$dependente1parente$$", "" + depentende1parente + "");

                            string dependente2parentes = myReader.GetString(34);
                            var dependente2parente = dependente2parentes.ToString();
                            document.ReplaceText("$$dependente2parente$$", "" + dependente2parente + "");

                            string dependente3parentes = myReader.GetString(37);
                            var dependente3parente = dependente3parentes.ToString();
                            document.ReplaceText("$$dependente3parente$$", "" + dependente3parente + "");

                            string dependente4parentes = myReader.GetString(40);
                            var dependente4parente = dependente4parentes.ToString();
                            document.ReplaceText("$$dependente4parente$$", "" + dependente4parente + "");

                            string dependente5parentes = myReader.GetString(43);
                            var dependente5parente = dependente5parentes.ToString();
                            document.ReplaceText("$$dependente5parente$$", "" + dependente5parente + "");

                            string dependente6parentes = myReader.GetString(46);
                            var dependente6parente = dependente6parentes.ToString();
                            document.ReplaceText("$$dependente6parente$$", "" + dependente6parente + "");

                            string dependente1nascs = myReader.GetString(32);
                            var dependente1nasc = dependente1nascs.ToString();
                            document.ReplaceText("$$dependente1nasc$$", "" + dependente1nasc + "");

                            string dependente2nascs = myReader.GetString(35);
                            var dependente2nasc = dependente2nascs.ToString();
                            document.ReplaceText("$$dependente2nasc$$", "" + dependente2nasc + "");

                            string dependente3nascs = myReader.GetString(38);
                            var dependente3nasc = dependente3nascs.ToString();
                            document.ReplaceText("$$dependente3nasc$$", "" + dependente3nasc + "");

                            string dependente4nascs = myReader.GetString(41);
                            var dependente4nasc = dependente4nascs.ToString();
                            document.ReplaceText("$$dependente4nasc$$", "" + dependente4nasc + "");

                            string dependente5nascs = myReader.GetString(44);
                            var dependente5nasc = dependente5nascs.ToString();
                            document.ReplaceText("$$dependente5nasc$$", "" + dependente5nasc + "");

                            string dependente6nascs = myReader.GetString(47);
                            var dependente6nasc = dependente6nascs.ToString();
                            document.ReplaceText("$$dependente6nasc$$", "" + dependente6nasc + "");

                            string datacadpiss = myReader.GetString(48);
                            var datacadpis = datacadpiss.ToString();
                            document.ReplaceText("$$datacadpis$$", "" + datacadpis + "");

                            string piss = myReader.GetString(49);
                            var pis = piss.ToString();
                            document.ReplaceText("$$pis$$", "" + pis + "");

                            string nobancopiss = myReader.GetString(50);
                            var nobancopis = nobancopiss.ToString();
                            document.ReplaceText("$$nobancopis$$", "" + nobancopis + "");

                            string endpiss = myReader.GetString(51);
                            var endpis = endpiss.ToString();
                            document.ReplaceText("$$endpis$$", "" + endpis + "");

                            string bancopiss = myReader.GetString(52);
                            var bancopis = bancopiss.ToString();
                            document.ReplaceText("$$bancopis$$", "" + bancopis + "");

                            string agpiss = myReader.GetString(53);
                            var agpis = agpiss.ToString();
                            document.ReplaceText("$$agpis$$", "" + agpis + "");

                            DateTime dataentradas = myReader.GetDateTime(54);
                            var dataentrada = dataentradas.ToShortDateString();
                            document.ReplaceText("$$dataentrada$$", "" + dataentrada + "");

                            DateTime dataentradalongas = myReader.GetDateTime(54);
                            var dataentradalonga = dataentradalongas.ToLongDateString();
                            document.ReplaceText("$$dataentradalonga$$", "" + dataentradalonga + "");

                            DateTime dataregs = myReader.GetDateTime(55);
                            var datareg = dataregs.ToShortDateString();
                            document.ReplaceText("$$datareg$$", "" + datareg + "");

                            string ocupacaos = myReader.GetString(56);
                            var ocupacao = ocupacaos.ToString();
                            document.ReplaceText("$$ocupacao$$", "" + ocupacao + "");

                            string secaos = myReader.GetString(57);
                            var secao = secaos.ToString();
                            document.ReplaceText("$$secao$$", "" + secao + "");

                            string salarioinicials = myReader.GetString(58);
                            var salarioinicial = salarioinicials.ToString();
                            document.ReplaceText("$$salarioinicial$$", "" + salarioinicial + "");

                            string comissoess = myReader.GetString(59);
                            var comissoes = comissoess.ToString();
                            document.ReplaceText("$$comissoes$$", "" + comissoes + "");

                            string tarefas = myReader.GetString(60);
                            var tarefa = tarefas.ToString();
                            document.ReplaceText("$$tarefa$$", "" + tarefa + "");

                            string formapagamentos = myReader.GetString(61);
                            var formapagamento = formapagamentos.ToString();
                            document.ReplaceText("$$formapagamento$$", "" + formapagamento + "");

                            string eoptantes = myReader.GetString(62);
                            var eoptante = eoptantes.ToString();
                            document.ReplaceText("$$eoptante$$", "" + eoptante + "");

                            DateTime dataopcaos = myReader.GetDateTime(63);
                            var dataopcao = dataopcaos.ToShortDateString();
                            document.ReplaceText("$$dataopcao$$", "" + dataopcao + "");

                            DateTime dataretratacaos = myReader.GetDateTime(64);
                            var dataretratacao = dataretratacaos.ToShortDateString();
                            document.ReplaceText("$$dataretratacao$$", "" + dataretratacao + "");

                            string bancodepositarios = myReader.GetString(69);
                            var bancodepositario = bancodepositarios.ToString();
                            document.ReplaceText("$$bancodepositario$$", "" + bancodepositario + "");

                            string hentradas = myReader.GetString(65);
                            var hentrada = hentradas.ToString();
                            document.ReplaceText("$$hentrada$$", "" + hentrada + "");


                            string halmocos = myReader.GetString(66);
                            var halmoco = halmocos.ToString();
                            document.ReplaceText("$$halmoco$$", "" + halmoco + "");


                            string hsaidas = myReader.GetString(67);
                            var hsaida = hsaidas.ToString();
                            document.ReplaceText("$$hsaida$$", "" + hsaida + "");


                            string dsrs = myReader.GetString(68);
                            var dsr = dsrs.ToString();
                            document.ReplaceText("$$dsr$$", "" + dsr + "");

                            DateTime datafimcontratos = myReader.GetDateTime(78);
                            var datafimcontrato = datafimcontratos.ToShortDateString();
                            document.ReplaceText("$$datafimcontrato$$", "" + datafimcontrato + "");
                        }

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



                    document.SaveAs(OutputFile);
                    MessageBox.Show("Ficha de Registro de "+vIDg2+" criada com sucesso!", "Aviso", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);

                } // Release this document from memory.


            }
        }
        else
        {

        }





    }

感谢您的帮助,为了简单起见,我相信我们应该更好地传播关于DocX的信息,因为老实说像我这样的新手,如果之前知道的话,不会因为互操作而浪费大量时间。

PS:如果你遇到问题,有时你的Word Interop工作与否,和/或当尝试使用互操作时应用程序崩溃,这是要走的路。