Thứ hai 10 Tháng bảy 2017 8. 24 giờ sáng
Shruti1009 thân mến,
Cảm ơn phản hồi của bạn.
Đây là mã C# để bạn tham khảo.
Mã. Chọn tất cả Document document = new Document[@"F:\sample.docx"];
List replacement = new List[];
//create a temp section to contains HTML
Section tempSection = document.AddSection[];
Paragraph p4 = tempSection.AddParagraph[];
p4.AppendHTML["your HTML"];
foreach [var par in tempSection.Paragraphs]
{
Paragraph para = par as Paragraph;
replacement.Add[para];
}
TextSelection[] selections = document.FindAllString["{{{wordToReplace}}}", false, true];
List locations = new List[];
foreach [TextSelection selection in selections]
{
locations.Add[new TextRangeLocation[selection.GetAsOneRange[]]];
}
locations.Sort[];
foreach [TextRangeLocation location in locations]
{
Replace[location, replacement];
}
//remove the temp section
document.Sections.Remove[tempSection];
document.SaveToFile["11052.docx",FileFormat.Docx];
}
private static void Replace[TextRangeLocation location, IList replacement]
{
//will be replaced
TextRange textRange = location.Text;
//textRange index
int index = location.Index;
//owener paragraph
Paragraph paragraph = location.Owner;
//owner text body
Body sectionBody = paragraph.OwnerTextBody;
//get the index of paragraph in section
int paragraphIndex = sectionBody.ChildObjects.IndexOf[paragraph];
int replacementIndex = -1;
if [index == 0]
{
//remove
paragraph.ChildObjects.RemoveAt[0];
replacementIndex = sectionBody.ChildObjects.IndexOf[paragraph];
}
else if [index == paragraph.ChildObjects.Count - 1]
{
paragraph.ChildObjects.RemoveAt[index];
replacementIndex = paragraphIndex + 1;
}
else
{
//split owner paragraph
Paragraph paragraph1 = [Paragraph]paragraph.Clone[];
while [paragraph.ChildObjects.Count > index]
{
paragraph.ChildObjects.RemoveAt[index];
}
int i = 0;
int count = index + 1;
while [i < count]
{
paragraph1.ChildObjects.RemoveAt[0];
i += 1;
}
sectionBody.ChildObjects.Insert[paragraphIndex + 1, paragraph1];
replacementIndex = paragraphIndex + 1;
}
//insert replacement
for [int i = 0; i index]
{
paragraph.ChildObjects.RemoveAt[index];
}
int i = 0;
int count = index + 1;
while [i < count]
{
paragraph1.ChildObjects.RemoveAt[0];
i += 1;
}
sectionBody.ChildObjects.Insert[paragraphIndex + 1, paragraph1];
replacementIndex = paragraphIndex + 1;
}
//insert replacement
for [int i = 0; i index]
{
paragraph.ChildObjects.RemoveAt[index];
}
int i = 0;
int count = index + 1;
while [i < count]
{
paragraph1.ChildObjects.RemoveAt[0];
i += 1;
}
sectionBody.ChildObjects.Insert[paragraphIndex + 1, paragraph1];
replacementIndex = paragraphIndex + 1;
}
//insert replacement
for [int i = 0; i