編輯文檔時,對一些需要修改的字符或段落可以通過查找替換的方式,快速地更改。在本篇文章中,將介紹如何用一篇Word文檔、圖片或者表格來替換文檔中的指定文本字符串。示例要點如下:
測試文檔:
using Spire.Doc;
using Spire.Doc.Interface;
namespace ReplaceTextWithDocument_Doc
{
class Program
{
static void Main(string[] args)
{
//加載源文檔
Document document = new Document("Original.docx");
//加載用于替換的文檔
IDocument replaceDocument = new Document("test.docx");
//用文檔替換源文檔中的指定文本
document.Replace("History", replaceDocument, false, true);
//保存文檔
document.SaveToFile("result.docx", FileFormat.Docx2013);
System.Diagnostics.Process.Start("result.docx");
}
}
}
替換結(jié)果:
測試文檔:
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System.Drawing;
namespace ReplaceTextWithImg_Doc
{
class Program
{
static void Main(string[] args)
{
//實例化Document類的對象,并加載測試文檔
Document doc = new Document();
doc.LoadFromFile("testfile.docx");
//加載替換的圖片
Image image = Image.FromFile("g.png");
//獲取第一個section
Section sec= doc.Sections[0];
//查找文檔中的指定文本內(nèi)容
TextSelection[] selections = doc.FindAllString("Google", true, true);
int index = 0;
TextRange range = null;
//遍歷文檔,移除文本內(nèi)容,插入圖片
foreach (TextSelection selection in selections)
{
DocPicture pic = new DocPicture(doc);
pic.LoadImage(image);
range = selection.GetAsOneRange();
index = range.OwnerParagraph.ChildObjects.IndexOf(range);
range.OwnerParagraph.ChildObjects.Insert(index, pic);
range.OwnerParagraph.ChildObjects.Remove(range);
}
//保存文檔
doc.SaveToFile("result.docx", FileFormat.Docx);
System.Diagnostics.Process.Start("result.docx");
}
}
}
替換結(jié)果:
測試文檔:
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
namespace ReplaceTextWithTable_Doc
{
class Program
{
static void Main(string[] args)
{
//實例化Document類的對象,并加載測試文檔
Document doc = new Document();
doc.LoadFromFile("test.docx");
//查找關(guān)鍵字符串文本
Section section = doc.Sections[0];
TextSelection selection = doc.FindString("參考附錄", true, true);
//獲取關(guān)鍵字符串所在的段落
TextRange range = selection.GetAsOneRange();
Paragraph paragraph = range.OwnerParagraph;
Body body = paragraph.OwnerTextBody;
int index = body.ChildObjects.IndexOf(paragraph);
//添加一個兩行三列的表格
Table table = section.AddTable(true);
table.ResetCells(2, 3);
range = table[0, 0].AddParagraph().AppendText("管號(McFarland)");
range = table[0, 1].AddParagraph().AppendText("0.5");
range = table[0, 2].AddParagraph().AppendText("1");
range = table[1, 0].AddParagraph().AppendText("0.25%BaCl2(ml)");
range = table[1, 1].AddParagraph().AppendText("0.2");
range = table[1, 2].AddParagraph().AppendText("0.4");
//移除段落,插入表格
body.ChildObjects.Remove(paragraph);
body.ChildObjects.Insert(index, table);
//保存文檔
doc.SaveToFile("result.doc", FileFormat.Doc);
System.Diagnostics.Process.Start("result.doc");
}
}
}
替換結(jié)果:
以上是本次關(guān)于“C# 用文檔、圖片、表格替換Word中的文本字符串的”的全部內(nèi)容。
(本文完)
創(chuàng)新互聯(lián)www.cdcxhl.cn,專業(yè)提供香港、美國云服務(wù)器,動態(tài)BGP最優(yōu)骨干路由自動選擇,持續(xù)穩(wěn)定高效的網(wǎng)絡(luò)助力業(yè)務(wù)部署。公司持有工信部辦法的idc、isp許可證, 機房獨有T級流量清洗系統(tǒng)配攻擊溯源,準(zhǔn)確進行流量調(diào)度,確保服務(wù)器高可用性。佳節(jié)活動現(xiàn)已開啟,新人活動云服務(wù)器買多久送多久。