将单词表单元格中的所有内容复制到单词文档的末尾



我需要对数千个word文档进行数据迁移。源文档包含具有单元格内容(文本、图像、对象等)的表。具有特定标题的表的内容需要复制到特定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();
            }
         }
     }
}

这对我有效:

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

最新更新