最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

C#操作實現(xiàn)Word全域查找且替換

 更新時間:2024年04月02日 08:35:42   作者:初九之潛龍勿用  
這篇文章主要為大家詳細(xì)介紹了C#如何操作實現(xiàn)Word全域查找且替換功能,文中的示例代碼講解詳細(xì),具有一定的借鑒價值,有需要的小伙伴可以參考下

關(guān)于全域查找且替換

C#全域操作 Word 查找且替換主要包括如下四個對象:

序號對象說明
1Word.Appication.Selection窗格對象
2Word.Section.Headers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range頁眉對象
3Word.Section.Footers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range頁腳對象
4Word.Shape.TextFrame.TextRange形狀對象

我們需要創(chuàng)建 Word.Find 對象,對上述相關(guān)區(qū)域分別進(jìn)行查找替換操作。

Word應(yīng)用樣本

我們假設(shè)設(shè)計簡歷模板的輸出,并查找且替換對應(yīng)的關(guān)鍵字,如下圖:

其中對應(yīng)項目的關(guān)鍵字如 {xm}、{xb} 等則為查找且替換的對象,{grzp} 關(guān)鍵字處我們要處理圖片的插入。

SqlServer數(shù)據(jù)表部分設(shè)計樣本

設(shè)計 PersonInfo 數(shù)據(jù)表如下:

CREATE TABLE [dbo].[PersonInfo](
	[id] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[sfzh] [varchar](18) NOT NULL,
	[xm] [nvarchar](50) NOT NULL,
	[xb] [nvarchar](1) NULL,
	[grzp] [image] NULL,
 CONSTRAINT [PK_PersonInfo] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [IX_PersonInfo] UNIQUE NONCLUSTERED 
(
	[sfzh] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
 
ALTER TABLE [dbo].[PersonInfo] ADD  CONSTRAINT [DF_PersonInfo_id]  DEFAULT (newid()) FOR [id]
GO

通過查詢 select sfzh,xm,xb,grzp from PersonInfo where id=xxx 得到DataSet,再取 Tables[0]中的數(shù)據(jù)。 

范例運行環(huán)境

操作系統(tǒng): Windows Server 2019 DataCenter

操作系統(tǒng)上安裝 Office Excel 2016

數(shù)據(jù)庫:Microsoft SQL Server 2016

.net版本: .netFramework4.7.1 或以上

開發(fā)工具:VS2019  C#

配置Office DCOM

配置方法可參照我的文章《C# 讀取Word表格到DataSet》進(jìn)行處理和配置。

設(shè)計實現(xiàn)

組件庫引入

實現(xiàn)原理

我們假設(shè)查詢出表數(shù)據(jù),存入對應(yīng)的變量,其中將二進(jìn)制字段grzp數(shù)據(jù)寫入到d:\test.jpg生成圖片,示例代碼如下:

DataTable dt=DataSet.Tables[0];
 
string sfzh = dt.Rows[0]["sfzh"].ToString();
object bt = dt.Rows[0]["grzp"];
byte[] bFile2 = (byte[])bt;
System.IO.File.WriteAllBytes("@d:\test.jpg", bFile2);
 
string xm = dt.Rows[0]["xm"].ToString();
string xb = dt.Rows[0]["xb"].ToString();

然后我們將其存到二維字符串?dāng)?shù)組 _repls 里,如下代碼:

string[,] _repls = new string[4, 2];
_repls[0, 0] = "{sfzh}";
_repls[0, 1] = sfzh;
_repls[1, 0] = "{xm}";
_repls[1, 1] = xm;
_repls[2, 0] = "{xb}";
_repls[2, 1] = xb;
_repls[3, 0] = "RepalceFromImageFilename_{grzp}";
_repls[3, 1] = "@d:\test.jpg";

其中第一元素存儲要查找的關(guān)鍵字,第二元素存儲要替換的值。注意:替換圖片使用了自定義的RepalceFromImageFilename_ 前綴關(guān)鍵字,則表示值為對應(yīng)的文件路徑。數(shù)據(jù)準(zhǔn)備完畢后,我們將通過遍歷數(shù)組對 Word 進(jìn)行查找且替換操作。

查找且替換的核心代碼

窗格內(nèi)容

示例代碼如下:

                WordApp.Options.ReplaceSelection = true;
                Word.Find fnd = WordApp.Selection.Find;
				for(int i=0;i<_repls.GetLength(0);i++)
				{
                    if (_repls[i, 0] == "" || _repls[i, 0] == null)
                    {
                        continue;
                    }
					fnd.ClearFormatting();
 
                    string ft = _repls[i, 0];
                    string replaceType = "";
                    if (ft.IndexOf("RepalceFromImageFilename_") == 0)
                    {
                        ft = ft.Replace("RepalceFromImageFilename_", "");
                        replaceType = "RepalceFromImageFilename";
                    }else if (ft.IndexOf("RepalceFromImageFilenameNoDelete_") == 0)
                    {
                        ft = ft.Replace("RepalceFromImageFilenameNoDelete_", "");
                        replaceType = "RepalceFromImageFilenameNoDelete";
                    }
                    Object findText = ft;
					Object matchCase = false;
					Object matchWholeWord = Type.Missing;
					Object matchWildcards = false;
					Object matchSoundsLike = false;
					Object matchAllWordForms = false;
					Object forward = true;
					Object wrap =Word.WdFindWrap.wdFindContinue;
					Object format = false;
					Object replaceWith ="";
					Object replace =Type.Missing;;
					Object matchKashida = Type.Missing;
					Object matchDiacritics = Type.Missing;
					Object matchAlefHamza = Type.Missing;
					Object matchControl = Type.Missing;
					while(fnd.Execute(ref findText, ref matchCase, ref matchWholeWord,ref matchWildcards, ref matchSoundsLike, ref matchAllWordForms, 
						ref forward, ref wrap, ref format, ref replaceWith,ref replace, ref matchKashida, ref matchDiacritics,ref matchAlefHamza, ref matchControl))
					{
 
						string r_f=WordApp.Selection.Font.Name.ToString();
                        if (replaceType == "RepalceFromImageFilename" || replaceType == "RepalceFromImageFilenameNoDelete")
                        {
                            if (File.Exists(_repls[i, 1].ToString()))
                            {
                                WordApp.Selection.Range.Select();
                                Word.InlineShape pic = WordApp.Selection.InlineShapes.AddPicture(_repls[i, 1].ToString(), false, true, WordApp.Selection.Range);
                                if (replConfigs != null)
                                {
                                    string[] cv = replConfigs[ft].Split('|');
                                    pic.Width = int.Parse(cv[0]);
                                    pic.Height = int.Parse(cv[1]);
 
                                }
                                if (replaceType == "RepalceFromImageFilename")
                                {
                                    File.Delete(_repls[i, 1].ToString());
                                }
                            }
                        }
                        else
                        {
                            WordApp.Selection.Range.Text = _repls[i, 1].ToString();
                        }
					
					}
				}

頁眉內(nèi)容

示例代碼如下:

                foreach (Word.Section header in WordDoc.Sections)
                {
                    Word.Range headerRange = header.Headers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
 
                    Word.Find fnd = headerRange.Find;
                    for (int i = 0; i < _repls.GetLength(0); i++)
                    {
                        if (_repls[i, 0] == "" || _repls[i, 0] == null)
                        {
                            continue;
                        }
                        fnd.ClearFormatting();
 
                        string ft = _repls[i, 0];
                        string replaceType = "";
                        if (ft.IndexOf("RepalceFromImageFilename_") == 0)
                        {
                            ft = ft.Replace("RepalceFromImageFilename_", "");
                            replaceType = "RepalceFromImageFilename";
                        }
                        else if (ft.IndexOf("RepalceFromImageFilenameNoDelete_") == 0)
                        {
                            ft = ft.Replace("RepalceFromImageFilenameNoDelete_", "");
                            replaceType = "RepalceFromImageFilenameNoDelete";
                        }
                        Object findText = ft;
                        Object matchCase = false;
                        Object matchWholeWord = Type.Missing;
                        Object matchWildcards = false;
                        Object matchSoundsLike = false;
                        Object matchAllWordForms = false;
                        Object forward = true;
                        Object wrap = Word.WdFindWrap.wdFindContinue;
                        Object format = false;
                        Object replaceWith = "";
                        Object replace = Type.Missing; ;
                        Object matchKashida = Type.Missing;
                        Object matchDiacritics = Type.Missing;
                        Object matchAlefHamza = Type.Missing;
                        Object matchControl = Type.Missing;
                        while (fnd.Execute(ref findText, ref matchCase, ref matchWholeWord, ref matchWildcards, ref matchSoundsLike, ref matchAllWordForms,
                            ref forward, ref wrap, ref format, ref replaceWith, ref replace, ref matchKashida, ref matchDiacritics, ref matchAlefHamza, ref matchControl))
                        {
 
                            string r_f = WordApp.Selection.Font.Name.ToString();
                            if (replaceType == "RepalceFromImageFilename" || replaceType == "RepalceFromImageFilenameNoDelete")
                            {
                                if (File.Exists(_repls[i, 1].ToString()))
                                {
                                    WordApp.Selection.Range.Select();
                                    Word.InlineShape pic = WordApp.Selection.InlineShapes.AddPicture(_repls[i, 1].ToString(), false, true, headerRange);
                                    if (replaceType == "RepalceFromImageFilename")
                                    {
                                        File.Delete(_repls[i, 1].ToString());
                                    }
                                }
                            }
                            else
                            {
                                headerRange.Text = _repls[i, 1].ToString();
                            }
 
                        }
                    }
                }

頁腳內(nèi)容

示例代碼如下:

                foreach (Word.Section footer in WordDoc.Sections)
                {
                    Word.Range footerRange = footer.Footers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
 
                    Word.Find fnd = footerRange.Find;
                    for (int i = 0; i < _repls.GetLength(0); i++)
                    {
                        if (_repls[i, 0] == "" || _repls[i, 0] == null)
                        {
                            continue;
                        }
                        fnd.ClearFormatting();
 
                        string ft = _repls[i, 0];
                        string replaceType = "";
                        if (ft.IndexOf("RepalceFromImageFilename_") == 0)
                        {
                            ft = ft.Replace("RepalceFromImageFilename_", "");
                            replaceType = "RepalceFromImageFilename";
                        }
                        else if (ft.IndexOf("RepalceFromImageFilenameNoDelete_") == 0)
                        {
                            ft = ft.Replace("RepalceFromImageFilenameNoDelete_", "");
                            replaceType = "RepalceFromImageFilenameNoDelete";
                        }
                        Object findText = ft;
                        Object matchCase = false;
                        Object matchWholeWord = Type.Missing;
                        Object matchWildcards = false;
                        Object matchSoundsLike = false;
                        Object matchAllWordForms = false;
                        Object forward = true;
                        Object wrap = Word.WdFindWrap.wdFindContinue;
                        Object format = false;
                        Object replaceWith = "";
                        Object replace = Type.Missing; ;
                        Object matchKashida = Type.Missing;
                        Object matchDiacritics = Type.Missing;
                        Object matchAlefHamza = Type.Missing;
                        Object matchControl = Type.Missing;
                        while (fnd.Execute(ref findText, ref matchCase, ref matchWholeWord, ref matchWildcards, ref matchSoundsLike, ref matchAllWordForms,
                            ref forward, ref wrap, ref format, ref replaceWith, ref replace, ref matchKashida, ref matchDiacritics, ref matchAlefHamza, ref matchControl))
                        {
 
                            string r_f = WordApp.Selection.Font.Name.ToString();
                            //						WordApp.Selection.Font.Name=r_f;
                            //						WordApp.Selection.Range
                            //						WordApp.Selection.TypeText(_repls[i,1].ToString());
                            if (replaceType == "RepalceFromImageFilename" || replaceType == "RepalceFromImageFilenameNoDelete")
                            {
                                if (File.Exists(_repls[i, 1].ToString()))
                                {
                                    WordApp.Selection.Range.Select();
                                    Word.InlineShape pic = WordApp.Selection.InlineShapes.AddPicture(_repls[i, 1].ToString(), false, true, footerRange);
                                    if (replaceType == "RepalceFromImageFilename")
                                    {
                                        File.Delete(_repls[i, 1].ToString());
                                    }
                                }
                            }
                            else
                            {
                                footerRange.Text = _repls[i, 1].ToString();
                            }
 
                        }
                    }
                }

形狀內(nèi)容

示例代碼如下:

                foreach (Word.Shape shape in WordDoc.Shapes)
                {
                    if (shape.TextFrame.HasText == 0)
                    {
                        continue; 
                    }
 
                    Word.Find fnd = shape.TextFrame.TextRange.Find;
                    //Word.Find fnd = WordDoc.Content.Find;
                    for (int i = 0; i < _repls.GetLength(0); i++)
                    {
                        if (_repls[i, 0] == "" || _repls[i, 0] == null)
                        {
                            continue;
                        }
                        fnd.ClearFormatting();
 
                        string ft = _repls[i, 0];
                        string replaceType = "";
                        if (ft.IndexOf("RepalceFromImageFilename_") == 0)
                        {
                            ft = ft.Replace("RepalceFromImageFilename_", "");
                            replaceType = "RepalceFromImageFilename";
                        }
                        else if (ft.IndexOf("RepalceFromImageFilenameNoDelete_") == 0)
                        {
                            ft = ft.Replace("RepalceFromImageFilenameNoDelete_", "");
                            replaceType = "RepalceFromImageFilenameNoDelete";
                        }
                        Object findText = ft;
                        Object matchCase = false;
                        Object matchWholeWord = Type.Missing;
                        Object matchWildcards = false;
                        Object matchSoundsLike = false;
                        Object matchAllWordForms = false;
                        Object forward = true;
                        Object wrap = Word.WdFindWrap.wdFindContinue;
                        Object format = false;
                        Object replaceWith = "";
                        Object replace = Type.Missing; ;
                        Object matchKashida = Type.Missing;
                        Object matchDiacritics = Type.Missing;
                        Object matchAlefHamza = Type.Missing;
                        Object matchControl = Type.Missing;
                        while (fnd.Execute(ref findText, ref matchCase, ref matchWholeWord, ref matchWildcards, ref matchSoundsLike, ref matchAllWordForms,
                            ref forward, ref wrap, ref format, ref replaceWith, ref replace, ref matchKashida, ref matchDiacritics, ref matchAlefHamza, ref matchControl))
                        {
 
                            string r_f = WordApp.Selection.Font.Name.ToString();
                            if (replaceType == "RepalceFromImageFilename" || replaceType == "RepalceFromImageFilenameNoDelete")
                            {
                                if (File.Exists(_repls[i, 1].ToString()))
                                {
                                    Word.InlineShape pic = WordApp.Selection.InlineShapes.AddPicture(_repls[i, 1].ToString(), false, true, shape.TextFrame.TextRange);
 
                                     
                                    if (replaceType == "RepalceFromImageFilename")
                                    {
                                        File.Delete(_repls[i, 1].ToString());
                                    }
                                }
                            }
                            else
                            {
                                shape.TextFrame.TextRange.Text = _repls[i, 1].ToString();
                            }
 
                        }
                    }
                }

小結(jié)

1、示例代碼是冗余的寫法,在實際應(yīng)用中我們需要進(jìn)行優(yōu)化。

2、添加圖片后,代碼默認(rèn)是使用完畢后,刪除圖片文件以釋放空間,我們自定義了 RepalceFromImageFilenameNoDelete_ 前綴關(guān)鍵字,表示使用完畢后不進(jìn)行文件刪除。

3、示例代碼中 Word 表示 using Word=Microsoft.Office.Interop.Word; 的引用。

4、示例代碼 WordDoc 表示對 Word.Document 的引用。

到此這篇關(guān)于C#操作實現(xiàn)Word全域查找且替換的文章就介紹到這了,更多相關(guān)C# Word全域查找且替換內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • c# 利用易福門振動模塊VSE002采集振動數(shù)據(jù)的方法

    c# 利用易福門振動模塊VSE002采集振動數(shù)據(jù)的方法

    這篇文章主要介紹了c# 利用易福門振動模塊VSE002采集振動數(shù)據(jù)的方法,本文通過圖文實例相結(jié)合給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-04-04
  • C#讀取計算機(jī)CPU及HDD信息的方法

    C#讀取計算機(jī)CPU及HDD信息的方法

    這篇文章主要介紹了C#讀取計算機(jī)CPU及HDD信息的方法,涉及C#讀取計算機(jī)CPU及硬盤信息的相關(guān)技巧,具有一定參考借鑒價值,需要的朋友可以參考下
    2015-07-07
  • C#?WinForm?RichTextBox文本動態(tài)滾動顯示文本方式

    C#?WinForm?RichTextBox文本動態(tài)滾動顯示文本方式

    這篇文章主要介紹了C#?WinForm?RichTextBox文本動態(tài)滾動顯示文本方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-03-03
  • C#使用Socket實現(xiàn)本地多人聊天室

    C#使用Socket實現(xiàn)本地多人聊天室

    這篇文章主要為大家詳細(xì)介紹了C#使用Socket實現(xiàn)本地多人聊天室,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2022-02-02
  • c#自定義泛型類的實現(xiàn)

    c#自定義泛型類的實現(xiàn)

    本篇文章是對c#中自定義泛型類的實現(xiàn)方法進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下
    2013-05-05
  • C# 禁止應(yīng)用程序多次啟動的實例

    C# 禁止應(yīng)用程序多次啟動的實例

    經(jīng)常我們會有這樣的需求,只讓應(yīng)用程序運行一個實體,下面是實現(xiàn)的方法,有需要的朋友可以參考一下
    2013-09-09
  • C# CultureInfo之常用InvariantCulture案例詳解

    C# CultureInfo之常用InvariantCulture案例詳解

    這篇文章主要介紹了C# CultureInfo之常用InvariantCulture案例詳解,本篇文章通過簡要的案例,講解了該項技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下
    2021-08-08
  • C#導(dǎo)出GridView數(shù)據(jù)到Excel文件類實例

    C#導(dǎo)出GridView數(shù)據(jù)到Excel文件類實例

    這篇文章主要介紹了C#導(dǎo)出GridView數(shù)據(jù)到Excel文件類,實例分析了C#使用GridView及Excel的技巧,具有一定參考借鑒價值,需要的朋友可以參考下
    2015-03-03
  • 輕松學(xué)習(xí)C#的密封類

    輕松學(xué)習(xí)C#的密封類

    輕松學(xué)習(xí)C#的密封類,對C#的密封類感興趣的朋友可以參考本篇文章,幫助大家更靈活的運用C#的密封類
    2015-11-11
  • C#編寫Windows服務(wù)實例代碼

    C#編寫Windows服務(wù)實例代碼

    本篇文章主要介紹使用Microsoft Visual Studio2012可以很方便的創(chuàng)建一個Windows服務(wù),本例實現(xiàn)一個向D盤的txt文件里,寫入系統(tǒng)時間的Windows服務(wù)
    2013-10-10

最新評論

青铜峡市| 漠河县| 盐城市| 丰台区| 格尔木市| 渭南市| 南乐县| 建平县| 青龙| 台山市| 旅游| 包头市| 奉新县| 浠水县| 汕尾市| 昭苏县| 治多县| 柏乡县| 井陉县| 古浪县| 周口市| 华安县| 三河市| 沐川县| 金华市| 长阳| 兴文县| 嵊泗县| 墨玉县| 化德县| 抚松县| 襄城县| 石屏县| 巫山县| 庆城县| 民县| 通州区| 靖安县| 天长市| 阳江市| 修水县|