簡體   English   中英

C#單詞自動化:將表復制並粘貼到新頁面中

[英]C# word automation: copy and paste a table into a new page

我將問題簡化如下:

我有一個帶有模板表的Word文檔。 該表有2行,包括標題和3列。 我想保留模板表的副本。 然后,我用數據填充原始表。 在那之后,我wqant通過插入分頁符打開一個新頁面和模板表粘貼到新的一頁。

我的代碼:

string filePath = Application.StartupPath + @"\docs\test.docx";
Word.Application wordApp = new Word.Application();
Word.Document wordDoc = wordApp.Documents.Open(filePath);
object oMissing = System.Reflection.Missing.Value;
wordApp.Visible = true;

//copy and keep template table
Word.Table templateTable = wordDoc.Tables[1];

//fill the table
Word.Cell cell;
cell = wordDoc.Tables[1].Cell(2, 1);
cell.Range.Text = "First Column...";
cell = wordDoc.Tables[1].Cell(2, 2);
cell.Range.Text = "Second Column...";
cell = wordDoc.Tables[1].Cell(2, 3);
cell.Range.Text = "Third Column...";

//insert a page break
wordDoc.Words.Last.InsertBreak(Word.WdBreakType.wdPageBreak);

//paste the template table in new page
Word.Range range = templateTable.Range;
range.Copy();
range.SetRange(templateTable.Range.End + 1, templateTable.Range.End + 1);
Word.Table tableCopy = wordDoc.Tables.Add(range, 1, 1, ref oMissing, ref oMissing);
tableCopy.Range.Paste();

問題:

  1. 粘貼已填充的表,而不是模板表
  2. 該表粘貼在第一個表之后,不在文檔末尾的新頁面中。

我嘗試了幾件事,但不知道如何解決該問題。
任何幫助都非常感謝。

感謝Francesco Baruchelli的帖子 ,我終於可以解決問題了:

解:

string filePath = Application.StartupPath + @"\docs\test.docx";
Word.Application wordApp = new Word.Application();
Word.Document wordDoc = wordApp.Documents.Open(filePath);
object oMissing = System.Reflection.Missing.Value;
wordApp.Visible = true;
Word.Selection selection = wordApp.Selection;

//copy and keep template table
var tableToUse = wordDoc.Tables[1];
//copy the empty table in the clipboard
Word.Range range = tableToUse.Range;
range.Copy();

//fill the original table
Word.Cell cell;
cell = wordDoc.Tables[1].Cell(2, 1);
cell.Range.Text = "First Column...";
cell = wordDoc.Tables[1].Cell(2, 2);
cell.Range.Text = "Second Column...";
cell = wordDoc.Tables[1].Cell(2, 3);
cell.Range.Text = "Third Column...";

//inserting a page break: first go to end of document
selection.EndKey(Word.WdUnits.wdStory, Word.WdMovementType.wdMove);
//insert a page break
object breakType = Word.WdBreakType.wdPageBreak;
selection.InsertBreak(ref breakType);

//paste the template table in new page
//add a new table (initially with 1 row and one column) at the end of the document
Word.Table tableCopy = wordDoc.Tables.Add(selection.Range, 1, 1, ref oMissing, ref oMissing);
//paste the original template table over the new one
tableCopy.Range.Paste();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM