繁体   English   中英

将多个docx文件合并为一个

[英]Merging multiple docx files to one

我正在用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);
            }
        }
    }

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

的1.instead 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.其他一些文档部分可能需要其他技术。

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

请参阅将多个Word文档合并到一个Open Xml中

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM