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

In my opinion it's not so easy. Therefore I'll give you some tips here. I think you need to implement the following changes to your code.

1.instead of pageBreak you need to add any of section breaks which could be the most appropriate:

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

and use this new variable within your loop. As a result you get all- text, footers and headers of the source document to new one.

2.However, you will still need to read margin parameters and apply them to your new document 'manually' using additional code. Therefore you will need to open source document and check it's margins in this way:

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

and next you need to apply it to new document, to appropriate section:

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

3.Some other document section could require some other techniques.

于 2013-10-20T10:23:58.593 に答える