Replacing content in Word 2010 Textboxes using OpenXML
Using the Open XML SDK I've been successful in programatically finding boo开发者_运维问答kmarks or text strings in a word document and inserting new content. I'm using OpenXmlPowerTools.SearchAndReplacer to do the text search and replace and this post's answer for the bookmarks Replace bookmark text in Word file using Open XML SDK
This all fails when the bookmark or the text I am trying to replace is located inside a Textbox.
Why does neither approach work within a Textbox? The Word documents I am trying to replace content within use Texboxes for layout and I can't work out what the problem is.
Does anybody have suggestions as to what might be the problem? Thanks
I did this - it works on text boxes in the case where there are not multiple runs with text (like 1 word bolded
Dim searchQuery = From tx In mainPart.Document.Body.Descendants(Of Text)()
Where tx.Text.Contains(replaceData.OldText)
Dim i As Integer
For i = 0 To searchQuery.Count - 1
searchQuery(i).Text = searchQuery(i).Text.Replace(replaceData.OldText, replaceData.NewText)
Next
Here is the XML for a simple textbox with the word test in it:
<w:pict xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
<v:shapetype id="_x0000_t202" coordsize="21600,21600" o:spt="202" path="m,l,21600r21600,l21600,xe" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:v="urn:schemas-microsoft-com:vml">
<v:stroke joinstyle="miter" />
<v:path gradientshapeok="t" o:connecttype="rect" />
</v:shapetype>
<v:shape id="_x0000_s1027" style="position:absolute;margin-left:0;margin-top:0;width:186.35pt;height:110.6pt;z-index:251660288;mso-width-percent:400;mso-height-percent:200;mso-position-horizontal:center;mso-width-percent:400;mso-height-percent:200;mso-width-relative:margin;mso-height-relative:margin" type="#_x0000_t202" xmlns:v="urn:schemas-microsoft-com:vml">
<v:textbox style="mso-fit-shape-to-text:t">
<w:txbxContent>
<w:p w:rsidR="00B558B5" w:rsidRDefault="00B558B5">
<w:proofErr w:type="gramStart" />
<w:r>
<w:t>test</w:t>
</w:r>
<w:proofErr w:type="gramEnd" />
</w:p>
</w:txbxContent>
</v:textbox>
</v:shape>
</w:pict>
You can see the structure is different then when searching for text within a bookmark since a textbox is actually stored as a picture. If you adjust your searching algorithm to deal with this different structure then you should be able to find the text and replace it.
精彩评论