2014-11-03 70 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(); 
} 
相关问题