2014-11-03 71 views
0

我需要對數千個單詞文檔進行數據遷移。源文檔包含具有單元格內容的表格(文本,圖像,對象等)。具有特定標題的表格的內容需要被複制到特定的Word文檔的末尾。在大多數情況下,內容將被複制到一個新文件中,但在某些情況下,相關的表格將其內容複製到同一個文件中,因此我需要知道如何粘貼到文件末尾。將單詞表格單元格中的所有內容複製到單詞文檔的末尾

我正在寫一個C#控制檯程序來執行此操作。現在我需要如何將表中的所有內容(不僅僅是文本)複製並粘貼到word文檔的末尾。

我可以打開相關文檔並選擇表格單元格,但我堅持要複製所有內容。這是將要進行復制的主要例程。

foreach (Table table in document.Tables) 
{ 
    for (int row = 1; row <= table.Rows.Count; row++) 
    { 
     var header = table.Cell(row, 1); 
     var headerText = header.Range.Text; 

     for(int j = 0; j < 3; j++) 
     { 
      // if contains header, write to new file 
      if (headerText.StartsWith(tableHeaders[j])) 
      { 
       // get new numbered file name 
       string filename = getFilename(targetDir, file, j + 1); 
       Console.WriteLine(filename); 

       //Create a new document 
       Document newDocument = application.Documents.Add(ref missing, ref missing, ref missing, ref missing); 

       // table cell to copy from: table.Cell(row + 1, 1) 
       // document to copy into: newDocument 
       // I am stuck here 

       // save file 
       newDocument.SaveAs2(filename); 
       newDocument.Close(); 
      } 
     } 
    } 
} 

回答

0

這爲我工作:

if (headerText.StartsWith(tableHeaders[j])) 
{ 
    // get file name 
    string filename = getFilename(targetDir, file, j + 1); 

    //Create a new document 
    Document newDocument = application.Documents.Add(ref missing, ref missing, ref missing, ref missing); 

    var copyFrom = table.Cell(row + 1, 1).Range; 
    int start = newDocument.Content.End - 1; 
    int end = newDocument.Content.End; 
    var copyTo = newDocument.Range(start, end); 

    copyFrom.MoveEnd(WdUnits.wdCharacter, -1); 
    copyTo.FormattedText = copyFrom.FormattedText; 

    // save file 
    newDocument.SaveAs2(filename); 
    newDocument.Close(); 
} 
相關問題