且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用C#表格粘贴到MS-Word文档的末尾

更新时间:2023-02-07 23:20:34

我已经找到了答案!



而不是使用Word.Range.Paste我用下面的:

 对象objUnit = Word.WdUnits.wdStory; 

oWord.Selection.EndKey(REF objUnit,裁判oMissing);

oWord.ActiveWindow.Selection.PasteAndFormat(Word.WdRecoveryType.wdPasteDefault);


I have a pre-made Word Template that has a table. I would like to open it up and then add (paste) another table at the end of the document. The problem is that it will not goto the end of the document, instead it paste the new table into the first cell of the original table. Any help would be greatly appreciated.

//previous code copied a table from another document

Object oTempPath = "C:\\Temp\\Logtemp.doc";
Object defaultTemplate = "C:\\Temp\\LogContemp.doc";


oDoc = oWord.Documents.Open(ref defaultTemplate,
                            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);



                        object start = oDoc.Content.Start;
                        object end = oDoc.Content.End; 
                        oDoc.Range(ref start, ref end).Copy();


                        oDoc.Close(ref oMissed, ref oMissed, ref oMissed);


                        oDoc = oWord.Documents.Open(ref oTempPath,
            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);

                        oDoc.Activate();

//**** This is where the issue starts ****

                        start = oWord.Selection.End;
                        end = oWord.Selection.End;



                       Word.Range rng = oDoc.Range(ref start, ref end);


                        rng.Select();
                        rng.Paste();


                        object fileN1 = "C:\\temp\\" + TextBox1.Text + " Log.doc";

                        oDoc.Fields.Update();
                        oDoc.SaveAs(ref fileN1,
                            ref oMissed, ref oMissed, ref oMissed, ref oMissed, ref oMissed,
                            ref oMissed, ref oMissed, ref oMissed, ref oMissed, ref oMissed,
                            ref oMissed, ref oMissed, ref oMissed, ref oMissed, ref oMissed);
                        oDoc.Close(ref oMissed, ref oMissed, ref oMissed);
                        oWord.Quit(ref oMissing, ref oMissing, ref oMissing);

I have found the answer!!

Instead of using Word.Range.Paste I used the following:

          Object objUnit = Word.WdUnits.wdStory;

          oWord.Selection.EndKey(ref objUnit, ref oMissing);

          oWord.ActiveWindow.Selection.PasteAndFormat(Word.WdRecoveryType.wdPasteDefault);