如何在OpenXML(C#.Net core 3.1)中用图像/表格替换文本

如何在OpenXML(C#.Net core 3.1)中用图像/表格替换文本,c#,openxml,openxml-sdk,C#,Openxml,Openxml Sdk,我只是使用OpenXML来处理docx文档。我有一些模板,它们的符号如下 {{userFirstName}} {{tableOfUsers}} {{signatureImage}}等 我需要用表格、图像等替换这些文本。如何在Openxml中做到这一点? 我正在使用C#.Net core 3.1和OpenXML 2.5 我的代码是这样的,但表仍然没有插入到正确的位置: var fileName = Path.Combine(_hostingEnv.WebRootPath, "te

我只是使用OpenXML来处理docx文档。我有一些模板,它们的符号如下 {{userFirstName}} {{tableOfUsers}} {{signatureImage}}等

我需要用表格、图像等替换这些文本。如何在Openxml中做到这一点? 我正在使用C#.Net core 3.1和OpenXML 2.5

我的代码是这样的,但表仍然没有插入到正确的位置:

    var fileName = Path.Combine(_hostingEnv.WebRootPath, "test/test.docx");
    var fileNameResult = Path.Combine(_hostingEnv.WebRootPath, "test/result.docx");

    byte[] byteArray = System.IO.File.ReadAllBytes(fileName);

    using (MemoryStream stream = new MemoryStream())
    {
        stream.Write(byteArray, 0, (int)byteArray.Length);
        using (WordprocessingDocument wd = WordprocessingDocument.Open(stream, true))
        {
            Table table = new Table();

            // Create a TableProperties object and specify its border information.
            TableProperties tblProp = new TableProperties(
                new TableBorders(
                    new TopBorder()
                    {
                        Val =
                        new EnumValue<BorderValues>(BorderValues.Dashed),
                        Size = 24
                    },
                    new BottomBorder()
                    {
                        Val =
                        new EnumValue<BorderValues>(BorderValues.Dashed),
                        Size = 24
                    },
                    new LeftBorder()
                    {
                        Val =
                        new EnumValue<BorderValues>(BorderValues.Dashed),
                        Size = 24
                    },
                    new RightBorder()
                    {
                        Val =
                        new EnumValue<BorderValues>(BorderValues.Dashed),
                        Size = 24
                    },
                    new InsideHorizontalBorder()
                    {
                        Val =
                        new EnumValue<BorderValues>(BorderValues.Dashed),
                        Size = 24
                    },
                    new InsideVerticalBorder()
                    {
                        Val =
                        new EnumValue<BorderValues>(BorderValues.Dashed),
                        Size = 24
                    }
                )
            );

            // Append the TableProperties object to the empty table.
            table.AppendChild<TableProperties>(tblProp);

            // Create a row.
            TableRow tr = new TableRow();

            // Create a cell.
            TableCell tc1 = new TableCell();

            // Specify the width property of the table cell.
            tc1.Append(new TableCellProperties(
                new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "2400" }));

            // Specify the table cell content.
            tc1.Append(new Paragraph(new Run(new Text("some text"))));

            // Append the table cell to the table row.
            tr.Append(tc1);

            // Create a second table cell by copying the OuterXml value of the first table cell.
            TableCell tc2 = new TableCell(tc1.OuterXml);

            // Append the table cell to the table row.
            tr.Append(tc2);

            // Append the table row to the table.
            table.Append(tr);  
            var tblStr = table.ToString();

            //wd.MainDocumentPart.Document.Body.Append(table);
            Text tablePl = wd.MainDocumentPart.Document.Body.Descendants<Text>().Where(x => x.Text == "{{tableOfUsers}}").First();
            if(tablePl != null)
            {
                var parent = tablePl.Parent;
                tablePl.Parent.InsertAfter<Table>(table, tablePl);
                tablePl.Remove();
            }

            string docText = null;
            using (StreamReader sr = new StreamReader(wd.MainDocumentPart.GetStream()))
            {
                docText = sr.ReadToEnd();
            }
            Regex regexText = new Regex("{{name}}");
            docText = regexText.Replace(docText, "Claire " + DateTime.Now.ToString());
            // Regex regextable = new Regex("{{tableOfUsers}}");
            // docText = regextable.Replace(docText, tblStr);


            using (StreamWriter sw = new StreamWriter(wd.MainDocumentPart.GetStream(FileMode.Create)))
            {
                sw.Write(docText);
            }
        }
        await System.IO.File.WriteAllBytesAsync(fileNameResult, stream.ToArray());
    }

    _fileRepo.SetPath("test");
    string fileName2 = "result.docx";
    var data = await _fileRepo.DownloadFile(fileName2);
    return File(data, "application/octet-stram", "filename.docx");
}
var fileName=Path.Combine(_hostingEnv.WebRootPath,“test/test.docx”);
var filenamesult=Path.Combine(_hostingEnv.WebRootPath,“test/result.docx”);
byte[]byteArray=System.IO.File.ReadAllBytes(文件名);
使用(MemoryStream stream=new MemoryStream())
{
stream.Write(byteArray,0,(int)byteArray.Length);
使用(WordprocessingDocument wd=WordprocessingDocument.Open(stream,true))
{
Table Table=新表();
//创建TableProperties对象并指定其边框信息。
TableProperties tblProp=新的TableProperties(
新台边(
新TopBorder()
{
瓦尔=
新枚举值(BorderValues.虚线),
尺寸=24
},
新边界()
{
瓦尔=
新枚举值(BorderValues.虚线),
尺寸=24
},
新LeftBorder()
{
瓦尔=
新枚举值(BorderValues.虚线),
尺寸=24
},
新右边界()
{
瓦尔=
新枚举值(BorderValues.虚线),
尺寸=24
},
新内部水平边界()
{
瓦尔=
新枚举值(BorderValues.虚线),
尺寸=24
},
新的InsideverticalOrder()
{
瓦尔=
新枚举值(BorderValues.虚线),
尺寸=24
}
)
);
//将TableProperties对象追加到空表。
表1.附录儿童(tblProp);
//创建一行。
TableRow tr=新的TableRow();
//创建一个单元格。
TableCell tc1=新的TableCell();
//指定表格单元格的宽度属性。
tc1.追加(新的TableCellProperties(
新的TableCellWidth(){Type=TableWidthUnitValues.Dxa,Width=“2400”});
//指定表格单元格内容。
tc1.追加(新段落(新运行(新文本(“某些文本”)));
//将表格单元格追加到表格行。
tr.Append(tc1);
//通过复制第一个表单元格的OuterXml值来创建第二个表单元格。
TableCell tc2=新的TableCell(tc1.OuterXml);
//将表格单元格追加到表格行。
tr.Append(tc2);
//将表行追加到表中。
表3.追加(tr);
var tblStr=table.ToString();
//wd.MainDocumentPart.Document.Body.Append(表);
Text tablePl=wd.MainDocumentPart.Document.Body.subjections()。其中(x=>x.Text==“{{tableOfUsers}}”).First();
if(tablePl!=null)
{
var parent=tablePl.parent;
tablePl.Parent.InsertAfter(table,tablePl);
tablePl.Remove();
}
字符串docText=null;
使用(StreamReader sr=newstreamreader(wd.MainDocumentPart.GetStream())
{
docText=sr.ReadToEnd();
}
Regex regexText=newregex(“{name}”);
docText=regexText.Replace(docText,“Claire”+DateTime.Now.ToString());
//Regex regextable=newregex(“{tableOfUsers}}”);
//docText=regextable.Replace(docText,tblStr);
使用(StreamWriter sw=newstreamwriter(wd.MainDocumentPart.GetStream(FileMode.Create)))
{
sw.Write(docText);
}
}
wait System.IO.File.WriteAllByteAsSync(fileNameResult,stream.ToArray());
}
_fileRepo.SetPath(“测试”);
字符串fileName2=“result.docx”;
var data=wait_fileRepo.DownloadFile(fileName2);
返回文件(数据,“application/octetstram”、“filename.docx”);
}
我的docx文件看起来像

你好{{name}

以下是用户列表:{{tableOfUsers}}

真诚地

{{signatureImage}}


使用以下代码插入表格:

............
string tablePlaceholder = "{{tableOfUsers}}";
Text tablePl = wd.MainDocumentPart.Document.Body
    .Descendants<Text>()
    .Where(x => x.Text.Contains(tablePlaceholder))
    .First();
if (tablePl != null)
{
    //Insert the table after the paragraph.
    var parent = tablePl.Parent.Parent.Parent;
    parent.InsertAfter(table, tablePl.Parent.Parent);
    tablePl.Text = tablePl.Text.Replace(tablePlaceholder, "");
    wd.MainDocumentPart.Document.Save();
}

string docText = wd.MainDocumentPart.Document.Body.OuterXml;
Regex regexText = new Regex("{{name}}");
docText = regexText.Replace(docText, "Claire " + DateTime.Now.ToString());
wd.MainDocumentPart.Document.Body = new Body(docText);
wd.MainDocumentPart.Document.Save();
.............
。。。。。。。。。。。。
字符串tablePlaceholder=“{tableOfUsers}}”;
Text tablePl=wd.MainDocumentPart.Document.Body
.后代()
.Where(x=>x.Text.Contains(tablePlaceholder))
.First();
if(tablePl!=null)
{
//在段落后插入表格。

var parent=tablePl.parent.parent.parent; parent.InsertAfter(表,tablePl.parent.parent); tablePl.Text=tablePl.Text.Replace(tablePlaceholder,“”); wd.MainDocumentPart.Document.Save(); } 字符串docText=wd.MainDocumentPart.Document.Body.OuterXml; Regex regexText=newregex(“{name}”); docText=regexText.Replace(docText,“Claire”+DateTime.Now.ToString()); wd.MainDocumentPart.Document.Body=新正文(docText); wd.MainDocumentPart.Document.Save(); .............

您正在代码中查找
{{table}
,但是模板中的符号是
{{tableOfUsers}

对不起,这是我的实验页面中的代码,我已经编辑过,因此它将适合当前的template@nightingale2k1我已经更新了答案,请查看。var parent=tablePl.parent.Pare