Spire.Doc is a professional Word .NET library specifically designed for developers to create, read, write, convert and print Word document files. Get free and professional technical support for Spire.Doc for .NET, Java, Android, C++, Python.

Mon Mar 27, 2023 4:35 am

Hi.

When using Replace as below, can I make it work only in a specific section, not all sections?.

Code: Select all
Document word = new Document();
word.LoadFromFile(filePath);
word.Replace($"t1", temp.Trim(), false, true);

Sungkyu_min
 
Posts: 36
Joined: Fri Jan 07, 2022 5:53 am

Mon Mar 27, 2023 8:28 am

Hi,

Thank you for your message.
Yes, the method you used cannot directly replace the content of special section. However, you can use the code below to replace content in a specific section.

Code: Select all
            Document word = new Document();
            word.LoadFromFile(@"Sample.docx");
            TextSelection[] textSelections = word.FindAllString("Word", true, true);
            foreach (TextSelection ts in textSelections)
            {
                Spire.Doc.Fields.TextRange textRange = ts.GetAsOneRange();
                Paragraph p = textRange.OwnerParagraph;
                Body ownerTextBody = p.OwnerTextBody;
                Section sec = (Section)ownerTextBody.Owner;
                int index = word.ChildObjects.IndexOf(sec);

                //set specipic section
                if (index == 0)
                {
                    textRange.Text = "newText";
                }
            }

            word.SaveToFile("newText.docx", FileFormat.Docx);


If you have any questions after the test, please provide your input file for further testing. you can upload it here or provide to us by email ([email protected]).

Best Regards,
Herman
E-iceblue support team
User avatar

Herman.Yan
 
Posts: 115
Joined: Wed Mar 08, 2023 2:00 am

Return to Spire.Doc

cron