2017-11-29 21 views
0

다음과 같이 문제를 단순화했습니다.

내부에 템플릿 테이블이있는 단어 문서가 있습니다. 표에는 머리글과 3 개의 열을 포함하는 2 개의 행이 있습니다. 템플릿 테이블의 사본을 보관하고 싶습니다. 그런 다음 원본 테이블에 데이터를 채 웁니다. 그 후, 페이지 나누기를 삽입하고 새 페이지에 템플릿 테이블을 붙여 넣어 새 페이지를 열지 않아도됩니다.

내 코드 :C# 단어 자동화 : 테이블을 복사하여 새 페이지에 붙여 넣기

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. 테이블은 끝이 아니라 새로운 페이지에서 첫 번째 테이블 후 붙여
  3. 문서의

몇 가지 시도했지만 문제를 해결하는 방법을 알아낼 수 없습니다.
도움이 매우 감사합니다.

답변

0

감사 Francesco Baruchelli's post에, 나는 마지막으로 문제를 해결할 수 :

솔루션 :

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();