0

我正在用 C# 开发一个桌面应用程序。我编写了一个函数来合并多个 docx 文件,但它没有按预期工作。我没有得到与源文件中的内容完全相同的内容。

中间添加了几行空行。内容延伸到下一页,页眉和页脚信息丢失,页边距更改等。我如何连接文档,因为它没有和更改它。任何建议都会有所帮助。

这是我的代码。

    public bool CombineDocx(string[] filesToMerge, string destFilepath)
    {
        Application wordApp = null;
        Document wordDoc = null;
        object outputFile = destFilepath;
        object missing = Type.Missing;
        object pageBreak = WdBreakType.wdPageBreak;

        try
        {
            wordApp = new Application { DisplayAlerts = WdAlertLevel.wdAlertsNone, Visible = false };
            wordDoc = wordApp.Documents.Add(ref missing, ref missing, ref missing, ref missing);

            Selection selection = wordApp.Selection;

            foreach (string file in filesToMerge)
            {
                selection.InsertFile(file, ref missing, ref missing, ref missing, ref missing);

                selection.InsertBreak(ref pageBreak);
            }

            wordDoc.SaveAs( ref outputFile, ref missing, ref missing, ref missing, 
                ref missing, ref missing, ref missing, ref missing, 
                ref missing, ref missing, ref missing, ref missing, 
                ref missing, ref missing, ref missing, ref missing);

            return true;
        }
        catch (Exception ex)
        {
            Msg.Log(ex);
            return false;
        }
        finally
        {
            if (wordDoc != null)
            {
                wordDoc.Close();
            }

            if (wordApp != null)
            {
                wordApp.DisplayAlerts = WdAlertLevel.wdAlertsAll;
                wordApp.Quit();
                Marshal.FinalReleaseComObject(wordApp);
            }
        }
    }
4

2 回答 2

0

在我看来,这并不容易。因此,我将在这里给您一些提示。我认为您需要对代码进行以下更改。

1. 而pageBreak不是您需要添加任何可能最合适的分节符:

object sectionBrak = WdBreakType.wdSectionBreakNextPage;
'other section break types also available

并在你的循环中使用这个新变量。结果,您可以将源文档的所有文本、页脚和页眉转换为新文档。

2.然而,您仍然需要阅读边距参数并使用附加代码“手动”将它们应用到您的新文档。因此,您将需要以这种方式打开源文档并检查其边距:

intLM = SourceDocument.Sections(1).PageSetup.LeftMargin;
'...and similar for other margins

接下来,您需要将其应用于新文档的相应部分:

selection.Sections(1).PageSetup.LeftMargin = intLM;

3.一些其他文档部分可能需要一些其他技术。

于 2013-10-20T10:23:58.593 回答
0

您可以使用 Open XML SDK 和 DocumentBuilder 工具。

请参阅将多个 word 文档合并为一个 Open Xml

于 2013-10-20T20:53:09.077 回答