首页 > 解决方案 > 打开 xml 2.5 查找具有特定字段代码的特定占位符。C#

问题描述

enter code here我有个问题。我在 word 中创建了一个名为 OrderLines 的特定属性,它包含一行三个单元格。我想克隆该行,然后我想进入克隆并更改所有三个具有 Text 属性的表格单元格 FieldCode。在该属性中,我想将 n1 更改为 n2。但只有克隆线。我的代码在所有包含 n1 的行上都发生了变化。我究竟做错了什么?

Body bod = doc.MainDocumentPart.Document.Body;
                    Table tables = bod.Descendants<Table>().First();
                    TableRow row = tables.Descendants<TableRow>().Last();
                    TableCell rowCell = new TableCell();
                    IEnumerable<FieldCode> placeHolder = mainPart.Document.Body.Descendants<FieldCode>();

                    // Denna tar fram TableProperties med namnet OrdeLines.
                    IEnumerable<TableProperties> tableProperties = mainPart.Document.Body.Descendants<TableProperties>().Where(tp => tp.TableCaption != null);
                    foreach (TableProperties tProp in tableProperties)
                    {
                        if (tProp.TableCaption.Val.Equals("OrderLines")) // see comment, this is actually StringValue
                        {

                            // do something for table with myCaption
                            Table table = (Table)tProp.Parent;
                            //Klonar sista raden
                            var cloneRow = table.ChildElements[3].CloneNode(true);
                            row.InsertAfterSelf(cloneRow);

                            foreach (TableCell tableCell in cloneRow)
                            { 
                                foreach (FieldCode code in placeHolder)
                                {   
                                    //var test = cloneRow.LastOrDefault().Where(x => x.InnerText == code.InnerText);

                                    var testo = tableCell.Parent.Descendants<FieldCode>().LastOrDefault().Where(X => X.InnerText == code.InnerText);

                                    if (testo != null)
                                    {
                                        code.Text = code.Text.Replace("n2_", "n1_");
                                    }
                                }
                            }
                        }

                    }

1):DOCPROPERTY "MFiles_PGB5E4D5DC229C4027AB19B40D0203C01Cn1_PG3E2BB7EBC49E4C8C825CCAE0AEBA9A06" * MERGEFORMAT

2):

在此处输入图像描述

3)在此处输入图片描述

        FieldCode fieldCode1 = new FieldCode(){ Space = SpaceProcessingModeValues.Preserve };
        fieldCode1.Text = " DOCPROPERTY  \"MFiles_PGB5E4D5DC229C4027AB19B40D0203C01Cn1_PG3E2BB7EBC49E4C8C825CCAE0AEBA9A06\"  \\* MERGEFORMAT ";

标签: c#ms-wordbackendopenxml-sdk

解决方案


推荐阅读