【问题标题】:How to programatically create Word's serial letter and store it as a single document?如何以编程方式创建 Word 序列号并将其存储为单个文档?
【发布时间】:2016-11-22 08:25:43
【问题描述】:

如何在 ASP.NET MVC 应用程序中生成 docx 序列号? 我可以通过将 docx 与 Content Controls 和 OpenXML 库一起使用,使用来自 DB 的数据填写一个简单的 docx 模板——例如 here 的建议。

但是,当尝试将其用于串行信件并将生成的文档合并到单个输出 docx(提示 here)时,生成的串行信件具有第一个条目的数据 - 例如当我为 10 名员工生成信函并提供此数据时,结果输出生成了 10 封信,但全部包含第一个员工的数据。

编辑:(添加示例代码)

internal static Stream CreateMultiPartDocument(IList<object> data, string templatePath)
{
    Stream mainDocumentStream = CreateTempDocument(data[0], templatePath);            

    for(int i = 1; i < data.Count; i++)
    {
        object childDocumentData = data[i];
        Stream childDocumentStream = CreateTempDocument(childDocumentData, templatePath);

        AppendChildDocument(mainDocumentStream, childDocumentStream);
    }

    mainDocumentStream.Flush();
    mainDocumentStream.Position = 0;

    return mainDocumentStream;
}


internal static Stream CreateTempDocument(object data, string templatePath)
{
    string fullTemplatePath = Path.Combine(TEMPLATE_BASE_PATH, templatePath);
    FileStream templateFile = File.Open(fullTemplatePath, FileMode.Open);

    if(null != templateFile)
    {                
        MemoryStream fileInMemory = new MemoryStream();
        templateFile.CopyTo(fileInMemory);

        string customXML = data.SerializeToXml();

        ReplaceCustomXmlInMemory(fileInMemory, customXML);
        fileInMemory.Flush();
        fileInMemory.Position = 0;

        templateFile.Close();
        return fileInMemory;
    }

    return null;
}

private static void ReplaceCustomXmlInMemory(MemoryStream fileInMemory, string customXML)
{
    using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(fileInMemory, true))
    {
        MainDocumentPart mainPart = wordDoc.MainDocumentPart;
        mainPart.DeleteParts(mainPart.CustomXmlParts);
        CustomXmlPart customXmlPart = mainPart.AddCustomXmlPart(CustomXmlPartType.CustomXml);
        using (StreamWriter streamWriter = new StreamWriter(customXmlPart.GetStream()))
        {
            streamWriter.Write(customXML);
        }

        wordDoc.Close();
    }
}

【问题讨论】:

  • 如果您为此编写了一些代码但无法使其工作,那么您来对地方了:只需将您的代码(或相关部分)添加到问题中即可。没有它,我们无能为力。请看stackoverflow.com/help/how-to-ask

标签: c# openxml docx contentcontrol


【解决方案1】:

我能找到的唯一解决方案是从 OpenXml 切换到 Syncfusion 的 FileFormats 库——它们从头开始支持邮件合并功能,可以使用多种输入格式。见链接here。 它也可以作为 Nuget 包使用,因此非常简单。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-11
    • 1970-01-01
    • 2010-09-07
    相关资源
    最近更新 更多