1

我正在使用 Novacode Docx 用 c# 创建 word 文档,但我在将两个文档合并为一个时遇到了问题。根据我的要求,我需要下载两个 word 文档而不一次压缩它们,但是我没有找到解决方案所以,我计划合并word文档并将它们下载为单个文件。有人可以帮助我如何使用Novacode Docx合并word文档。

先感谢您。

4

1 回答 1

1

我这样做:

private DocX fullReportDocument;
private DocX titleDocument;
private DocX firstDocument;
private DocX secondDocument;

public byte[] GetReport(bool WantFirstReport, bool WantSecondReport)
{

    fullDocument = DocX.Create(new MemoryStream());
    // Create title for the report
    this.GenerateTitleDocument();
    // Insert the old document into the new document.
    fullDocument.InsertDocument(titleDocument);

    // Save the new document.
    fullDocument.Save();

    if (WantFirstReport)
    {
        // Create expertise report
        this.GenrateFirstDocument();

        // Insert a page break at the beginning to separate title and expertise report properly
        firstDocument.Paragraphs[0].InsertPageBreakBeforeSelf();
        firstDocument.Save();

        // Insert the old document into the new document.
        fullDocument.InsertDocument(firstDocument);

        // Save the new document.
        fullDocument.Save();
    }

    if (WantSecondReport)
    {
        // Create expertise report
        this.GenrateSecondDocument();

        // Insert a page break at the beginning to separate title and expertise report properly
        secondDocument.Paragraphs[0].InsertPageBreakBeforeSelf();
        secondDocument.Save();

        // Insert the old document into the new document.
        fullDocument.InsertDocument(secondDocument);

        // Save the new document.
        fullDocument.Save();
    }
    return fullReportDocument.DocumentMemoryStream.ToArray();
}

但我修改了 DocX 库以添加 DocumentMemoryStream 属性,该属性公开 memoryStream 内部 MemoryStream

如果您不想修改 DocX 库,您也可以这样做:

fullDocument.SaveAs(GENERATED_DOCX_LOCATION);
return System.IO.File.ReadAllBytes(GENERATED_DOCX_LOCATION);

GENERATED_DOCX_LOCATION 显然是一个字符串,其中包含您要保存的文件的物理路径。

于 2017-10-03T12:11:47.477 回答