【问题标题】:Copy all content from a word table cell into the end of a word document将 word 表格单元格中的所有内容复制到 word 文档的末尾
【发布时间】:2014-12-29 20:48:57
【问题描述】:

我需要对数千个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();
            }
         }
     }
}

【问题讨论】:

    标签: c# ms-word


    【解决方案1】:

    这对我有用:

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

    【讨论】:

      猜你喜欢
      • 2018-07-05
      • 2022-10-04
      • 1970-01-01
      • 2016-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多