簡體   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