通过OpenXML生成word文档

Generate word doc through OpenXML

我有一个 ASP.NET 4.5 Web 表单应用程序,运行 在 IIS 7.5 上。

我正在尝试从其中一个我有自定义表单的页面生成一个 word 文档。

我上传了一个包含合并字段的 word 文档模板。 在后面的代码中,我想根据 sql 数据库查询填充合并字段。

对于某些合并字段,我需要插入多行文本。其中一些甚至有项目符号列表。这些文本片段我无法存储在 sql 中,所以我将它们添加到带有书签的单独 word 文档中。

所以,简单回顾一下:

Template.dotx -> 包含合并字段

Data.docx -> 包含已用书签标记的文本片段。

我已经设法使用 OpenXML 替换了 Template.dotx 中的合并字段,但是我找不到将书签中的数据导入合并字段的方法。

这对 Interop 非常有效,但是当我将它上传到服务器时遇到问题,所以我切换到 OpenXML。

这是我目前尝试过的方法:

private string GetBookmarkData(WordprocessingDocument secondWordDoc, string bookmarkKey)
    {
            string returnVal = "";
            foreach (BookmarkStart bookmarkStart in secondWordDoc.MainDocumentPart.RootElement.Descendants<BookmarkStart>())
            {
                if(bookmarkStart.Name == bookmarkKey)
                {
                    foreach(Run run in bookmarkStart.Parent.Descendants<Run>())
                    {
                        returnVal += run.Descendants<Text>().FirstOrDefault().Text + "<br/>";
                    }
                }
            }
            return returnVal;
        }
    
    
    protected void PrintBtn_Click(object sender, EventArgs e)
    {
                string mainTemplate = Server.MapPath("~/MyFolder/Template.dotx");
                string savePath = Server.MapPath("~/SaveFolder/Final.docx");
    
                File.Copy(mainTemplate, savePath);
                using(WordprocessingDocument firstDoc = WordprocessingDocument.Open(savePath, true))
                {
                    using (WordprocessingDocument secondDoc = WordprocessingDocument.Open(Server.MapPath("~/MyFolder/Data.docx"), true))
                    {
                        foreach (FieldCode field in firstDoc.MainDocumentPart.RootElement.Descendants<FieldCode>())
                        {
                            var fieldNameStart = field.Text.LastIndexOf(" MERGEFIELD", System.StringComparison.Ordinal);
                            String fieldText = field.InnerText;
                            if (fieldText.StartsWith(" MERGEFIELD"))
                            {
                                Int32 endMerge = fieldText.IndexOf("\");
                                Int32 fieldNameLength = fieldText.Length - endMerge;
                                String fieldName = fieldText.Substring(11, endMerge - 11);
                                fieldName = fieldName.Trim();
                                string autoFill = "";
    
                                    switch (fieldName)
                                    {
                                        case "MergeField1":
                                            autoFill = mergefield_1;
                                            break;
                                        case "MergeField2":
                                            autoFill = mergefield_2;
                                            break;
                                        case "MergeField3":
                                            autoFill = GetBookmarkData(secondDoc, "Bookmark1");
                                            break;
                                        case "MergeField4":
                                            autoFill = GetBookmarkData(secondDoc, "Bookmark2");
                                            break;
                                        case "MergeField5":
                                            autoFill = GetBookmarkData(secondDoc, "Bookmark3");
                                            break;
                                  }
                            }
    
                            foreach (Run run in firstDoc.MainDocumentPart.Document.Descendants<Run>())
                            {
                               foreach (Text txtFromRun in run.Descendants<Text>().Where(a => a.Text == "«" + fieldName + "»"))
                               {
                                  txtFromRun.Text = autoFill;
                               }
                            }
                        }
                    } 
                }
                            
        firstDoc.ChangeDocumentType(WordprocessingDocumentType.Document);
        firstDoc.MainDocumentPart.Document.Save();
    }
}

那么这是做什么的?

当我点击一个按钮时,我调用方法PrintBtn_Click。在做了一些 SQL 魔术(我没有包括在其中)之后,我初始化了一些变量,这些变量将填充每个合并字段。这个例子是一个简短的编辑版本。原来的要大得多。使用此代码,我设法填充了合并字段。它很好用。然而方法:`

string GetBookmarkData(WordprocessingDocument secondWordDoc, string bookmarkKey)`

并没有真正做到它应该做的。它应该进入 Data.docx,从我指定的书签中检索所有文本。它只有 returns 没有项目符号或奇怪格式的行。

我在 Interop 上使用了相同的过程,没有遇到任何问题。我如何使用 OpenXML 执行此操作?带有项目符号的行是否存储在不同的 xml 中?

我试图检索 BookmarkStart 和 BookmarkEnd 之间的所有运行并从中获取文本。

更新

secondDoc 实际上是 Data.docx,看起来像这样:

Bookmark1

•   Text-Information 1 (This is just an example)
•   Text-Information 2 (This is just an example)
•   Text-Information 3 (This is just an example)
•   Text-Information 4 (This is just an example)

Bookmark2

This is a list of multiple items:
Item 1                              x.000,00 
Item 2                              x.000,00 
Item 3                              x.000,00 
Item 4                              x.000,00 
Item 5                              000,00 
This is the conclusion for this list.

Following is a list of other multiple items:
Item 1                              x.000,00 
Item 2                              x.000,00 
Item 3                              x.000,00 
Item 4                              x.000,00 
Item 5                              000,00 
This is the conclusions for this list


Bookmark3

a)  Another example of text that needs to go in the mergefield:
•   Article 1 xxxx  Quantity/Producer etc
•   Article 2 xxxx  Quantity/Producer etc
Some details about this block of text that is not relevant but I need to insert it in the merge field as well

因此,如果按下某个单选按钮,则“Bookmark1”/“Bookmark2”/“Bookmark3”之后的整个文本需要进入其特定的合并字段。我已将这些文本块添加为书签。正如我上面告诉你的,它只插入一些没有项目符号的行。例如,对应于 Bookmark2 的合并字段仅接收“这是一个包含多个项目的列表:”。

查看您的文档和代码,我发现有两个地方可能是您问题的根源:

首先:包含Bookmark1 的SecondTemplate.docx 的xml 布局如下所示:

<Paragraph>
    <Bookmarkstart name=bookmark1/>
    <Run>
        <Text "Item 1">
    </Run>
</Paragraph>
<Paragraph>
    <Run>
        <Text "Item 2">
    </Run>
</Paragraph>    
<Paragraph>
    <Run>
        <Text "Item 3">
    </Run>
</Paragraph>    
<Paragraph>
    <Run>
        <Text "Item 4">
    </Run>
    <Bookmarkend/>
</Paragraph>    

和您的代码:

            if(bookmarkStart.Name == bookmarkKey)
            {
                foreach(Run run in bookmarkStart.Parent.Descendants<Run>())
                {
                    returnVal += run.Descendants<Text>().FirstOrDefault().Text + "<br/>";
                }
            }

bookmarkstart.Parent 调用运行时,它匹配书签正上方的 Paragraph :

<Paragraph>
    <Bookmarkstart name=bookmark1/>
    <Run>
        <Text "Item 1">
    </Run>
</Paragraph>

所以当循环的其余部分执行时,您只会将 "Item 1" 拉入合并过程。对于 BookmarkStart 和 BookmarkEnd 之间的所有四个段落,您需要重新处理逻辑以正确匹配 运行 中的文本。

其次: 在 OpenXml 中经常让人们感到困惑的另一个问题是,当您试图匹配 Descendants 调用中的 Run 时:

 bookmarkStart.Parent.Descendants<Run>

如果您指的是 DocumentFormat.OpenXml.Drawing.Run 而不是正确的 'DocumentFormat.OpenXml.Wordprocessing.Run',这会阻止匹配 - 所以将鼠标悬停在 Visual Studio 中的 Run 上并确保您匹配正确的 运行。调整您的 using 语句以获得正确的语句。像

这样的 Using 语句
using Run = DocumentFormat.OpenXml.Wordprocessing.Run;

经常使用,具体取决于该文件中的其余代码。希望这些线索对你有所帮助。