人妻夜夜爽天天爽三区丁香花-人妻夜夜爽天天爽三-人妻夜夜爽天天爽欧美色院-人妻夜夜爽天天爽免费视频-人妻夜夜爽天天爽-人妻夜夜爽天天

LOGO OA教程 ERP教程 模切知識交流 PMS教程 CRM教程 開發(fā)文檔 其他文檔  
 
網(wǎng)站管理員

C#操作實現(xiàn)微軟Office的Word全域查找且替換指定文本內容

admin
2025年1月14日 15:39 本文熱度 248

關于全域查找且替換

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 對象,對上述相關區(qū)域分別進行查找替換操作。

Word應用樣本

我們假設設計簡歷模板的輸出,并查找且替換對應的關鍵字,如下圖:

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

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

設計 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》進行處理和配置。

設計實現(xiàn)

組件庫引入

實現(xiàn)原理

我們假設查詢出表數(shù)據(jù),存入對應的變量,其中將二進制字段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();

然后我們將其存到二維字符串數(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";

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

查找且替換的核心代碼

窗格內容

示例代碼如下:

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();

        }

    }

}

頁眉內容

示例代碼如下:

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();

            }

        }

    }

}

頁腳內容

示例代碼如下:

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();

            }

        }

    }

}

形狀內容

示例代碼如下:

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();

            }

        }

    }

}

小結

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

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

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

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


該文章在 2025/1/14 15:39:43 編輯過
關鍵字查詢
相關文章
正在查詢...
點晴ERP是一款針對中小制造業(yè)的專業(yè)生產(chǎn)管理軟件系統(tǒng),系統(tǒng)成熟度和易用性得到了國內大量中小企業(yè)的青睞。
點晴PMS碼頭管理系統(tǒng)主要針對港口碼頭集裝箱與散貨日常運作、調度、堆場、車隊、財務費用、相關報表等業(yè)務管理,結合碼頭的業(yè)務特點,圍繞調度、堆場作業(yè)而開發(fā)的。集技術的先進性、管理的有效性于一體,是物流碼頭及其他港口類企業(yè)的高效ERP管理信息系統(tǒng)。
點晴WMS倉儲管理系統(tǒng)提供了貨物產(chǎn)品管理,銷售管理,采購管理,倉儲管理,倉庫管理,保質期管理,貨位管理,庫位管理,生產(chǎn)管理,WMS管理系統(tǒng),標簽打印,條形碼,二維碼管理,批號管理軟件。
點晴免費OA是一款軟件和通用服務都免費,不限功能、不限時間、不限用戶的免費OA協(xié)同辦公管理系統(tǒng)。
Copyright 2010-2025 ClickSun All Rights Reserved

主站蜘蛛池模板: 妖精视频一区二区三区 | 国产精品剧情原创麻豆国产 | 国产欧美一区二区久久 | 国产精品久久综合桃花网 | 精品无码av中文无码版 | 亚色九九九全国免费视频 | 久久99精品一久久久久久 | 国产人妻大保健私密推油按摩无码 | 日本护士在线播放 | 桃色AV久久无码线观看 | 亚洲 欧美 影音先锋 | 亚洲日韩av无码不卡一区二区三区 | 四虎国产精品免费五月天 | 亚洲自拍清纯综合图区 | 国产国产人免费人成成免视频 | 国产精品久久久久久无码不卡 | 欧美午夜日韩福利 | 欧美日韩精品一区二区三区激情在线 | 色情欧美片午夜国产特黄 | 成人综合天天影院 | 日韩国产二区不卡在线 | 欧美亚洲每日更新在线日韩 | 成a人影片免费观看日本 | 性一乱一交A片 | 亚洲成 人图片综合网 | 日韩产品和欧美产品的区别视频 | 一区二区高清 | 日韩一区二区三区中文 | 久久久精品午夜日韩欧美另类中 | 99久久精品看国产一区 | 美女网站免费福利视频 | 国产女人与黑人在线播放 | 99久久免费精品视香蕉蕉 | 岛国在线观看一区二区三区 | 亚洲欧美丝袜久久精品 | snh48亚洲大片免费国产 | 久久久久久亚洲aⅴ无码软件 | 亚洲男女一区二区三区 | 麻豆精品无人区码一二三区别:三大区域解析 | 波多野结衣中文丝袜字幕 | 国产交换配乱吟视频老人 |