使用C#对Word进行读写、搜索、插入图片等操作

一、C#中操作word的三种插件

使用C#对word文档进行读写,方法有:
1、通过office组件,在C#中添加dll引用,这种方法需要电脑先安装office软件,然后才能调用;
2、通过NPOI组件,NPOI组件是开源而且免费的,可以在VS中通过nuget包管理器进行下载安装插件;
3、使用Spire组件,Spire组件是一个企业级的.NET Office操作组件,既有收费版本又有免费版本,使用免费版本即可满足日常使用要求。打开nuget包管理器,搜索freespire.doc,如下图所示,点击第一个搜索项进行安装即可。
在这里插入图片描述

二、创建和保存word文档

1、使用office组件,代码如下:

using MSWord = Microsoft.Office.Interop.Word;
MSWord.Application wordApp = new MSWord.ApplicationClass(); //初始化Word应用程序变量 
wordApp.Visible = true;//设置文档是否可见
//由于使用的是COM库,因此有许多变量需要用Missing.Value代替
Object Nothing = Missing.Value;
MSWord.Document wordDoc = wordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);//新建Word文档
wordDoc.SaveToFile("OperateWord.docx", FileFormat.Docx);//保存文档,文件名和文件格式

注:当初始化Word应用程序变量时,可能会报出“无法嵌入互操作类型“ApplicationClass”。请改用适用的接口”错误,这时需要在引用中找到Microsoft.Office.Interop.Word ,修改属性“嵌入互操作类型”为false即可,具体见无法嵌入互操作类型“ApplicationClass”。请改用适用的接口
2、使用spire组件,代码如下:

using DocWord = Spire.Doc;
DocWord.Document doc = new DocWord.Document();//新建Word文档
string filepath =  "C:\\Users\Administrator\\Desktop\\test.docx";//Word文档地址
doc.LoadFromFile(filepath, DocWord.FileFormat.Docx);//读取Word文档
DocWord.Document doc01 = new DocWord.Document(filepath, DocWord.FileFormat.Docx);//也可以初始化时读取Word文档
doc01.SaveToFile("OperateWord.docx", FileFormat.Docx);//保存文档,文件名和文件格式

三、页面设置

1、使用office组件,代码如下:

#region 页面设置、页眉图片和文字设置,最后跳出页眉设置

//页面设置
wordDoc.PageSetup.PaperSize = MSWord.WdPaperSize.wdPaperA4;//设置纸张样式为A4纸
wordDoc.PageSetup.Orientation = MSWord.WdOrientation.wdOrientPortrait;//排列方式为垂直方向
wordDoc.PageSetup.TopMargin = 57.0f;
wordDoc.PageSetup.BottomMargin = 57.0f;
wordDoc.PageSetup.LeftMargin = 57.0f;
wordDoc.PageSetup.RightMargin = 57.0f;
wordDoc.PageSetup.HeaderDistance = 30.0f;//页眉位置

//设置页眉
wordApp.ActiveWindow.View.Type = MSWord.WdViewType.wdNormalView;//普通视图(即页面视图)样式
wordApp.ActiveWindow.View.SeekView = MSWord.WdSeekView.wdSeekPrimaryHeader;//进入页眉设置,其中页眉边距在页面设置中已完成
wordApp.Selection.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphRight;//页眉中的文字右对齐

//插入页眉图片(测试结果图片未插入成功)
wordApp.Selection.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphCenter;
string headerfile = @"C:\Users\xiahui\Desktop\OficeProgram\3.jpg";
MSWord.InlineShape shape1 = wordApp.ActiveWindow.ActivePane.Selection.InlineShapes.AddPicture(headerfile, ref Nothing, ref Nothing, ref Nothing);
shape1.Height = 5;//强行设置貌似无效,图片没有按设置的缩放——图片的比例并没有改变。
shape1.Width = 20;
wordApp.ActiveWindow.ActivePane.Selection.InsertAfter("  文档页眉");//在页眉的图片后面追加几个字

//去掉页眉的横线
wordApp.ActiveWindow.ActivePane.Selection.ParagraphFormat.Borders[MSWord.WdBorderType.wdBorderBottom].LineStyle = MSWord.WdLineStyle.wdLineStyleNone;
wordApp.ActiveWindow.ActivePane.Selection.Borders[MSWord.WdBorderType.wdBorderBottom].Visible = false;
wordApp.ActiveWindow.ActivePane.View.SeekView = MSWord.WdSeekView.wdSeekMainDocument;//退出页眉设置
#endregion

#region 页码设置并添加页码

//为当前页添加页码
MSWord.PageNumbers pns = wordApp.Selection.Sections[1].Headers[MSWord.WdHeaderFooterIndex.wdHeaderFooterEvenPages].PageNumbers;//获取当前页的号码
pns.NumberStyle = MSWord.WdPageNumberStyle.wdPageNumberStyleNumberInDash;//设置页码的风格,是Dash形还是圆形的
pns.HeadingLevelForChapter = 0;
pns.IncludeChapterNumber = false;
pns.RestartNumberingAtSection = false;
pns.StartingNumber = 0; //开始页页码?
object pagenmbetal = MSWord.WdPageNumberAlignment.wdAlignPageNumberCenter;//将号码设置在中间
object first = true;
wordApp.Selection.Sections[1].Footers[MSWord.WdHeaderFooterIndex.wdHeaderFooterEvenPages].PageNumbers.Add(ref pagenmbetal, ref first);

#endregion

2、使用spire组件,代码如下:

DocWord.Section section0 = doc.AddSection();
section0.PageSetup.Orientation = DocWord.Documents.PageOrientation.Landscape;//排列方式为横版
DocWord.Documents.Paragraph paragraph = section0.AddParagraph();//增加一个段落
paragraph.AppendBreak(DocWord.Documents.BreakType.PageBreak);//插入分页符

四、读写文本

1、使用office组件,代码如下:

strContent = "我是普通文本\n";
wordDoc.Paragraphs.Last.Range.Text = strContent;
wordDoc.Paragraphs.Last.Range.Text = "我再加一行试试,这里不加'\\n'";
//直接添加段,不是覆盖( += )
wordDoc.Paragraphs.Last.Range.Text += "不会覆盖的,";
//添加在此段的文字后面,不是新段落
wordDoc.Paragraphs.Last.Range.InsertAfter("这是后面的内容\n");

2、使用spire组件,代码如下:

DocWord.Section section0 = doc.AddSection();
DocWord.Documents.Paragraph paragraph = section0.AddParagraph();
paragraph.AppendText("hello world");//写入文本
StringBuilder sb = new StringBuilder();
//遍历节和段落,获取段落中的文本
foreach (Section section in document.Sections)
{
    foreach (Paragraph paragraph in section.Paragraphs)
    {
        sb.AppendLine(paragraph.Text);
    }
}
File.WriteAllText("文本2.txt", sb.ToString());

五、搜索功能

1、使用office组件,代码如下:

int i = 0;
int iCount = 0 ;
Word.Find wfnd;
if(wd.Paragraphs != null  && wd.Paragraphs.Count > 0 )
{
    iCount=wd.Paragraphs.Count;
    for(i=1;i<=iCount;i++)
    {
        wfnd=wd.Paragraphs[i].Range.Find;
        wfnd.ClearFormatting();
        wfnd.Text=strKey;
        if (wfnd.Execute(ref MissingValue,ref MissingValue,
               ref MissingValue,ref MissingValue,
               ref MissingValue,ref MissingValue,
               ref MissingValue,ref MissingValue,
               ref MissingValue,ref MissingValue,
               ref MissingValue,ref MissingValue,
               ref MissingValue,ref MissingValue,
               ref MissingValue))
        {
               MessageBox.Show("文档中包含指定的关键字!","搜索结果",MessageBoxButtons.OK);
               break;
        }
    }
}

2、使用spire组件,代码如下:

string findkey = "hello";
//查找一个特定字符串 ”Spire.Doc”
TextSelection selection = document.FindString(findkey, false, true);
TextRange range = selection.GetAsOneRange();

//替换字符串
range.Text = "word";//将hello替换为word

//设置高亮颜色
range.CharacterFormat.HighlightColor = Color.Yellow;

//查找文档中所有字符串 ”Microsoft”
TextSelection[] text = document.FindAllString("Microsoft", false, true);

//设置高亮颜色
foreach (TextSelection seletion in text)
{
    seletion.GetAsOneRange().CharacterFormat.HighlightColor = Color.Green;
}

六、插入图片

1、使用office组件,代码如下:

string FileName = Environment.CurrentDirectory + "\\6.jpg";//图片所在路径
object LinkToFile = false;
object SaveWithDocument = true;
object Anchor = table.Cell(tableRow + 1, tableColumn).Range;//选中要添加图片的单元格
wordDoc.Application.ActiveDocument.InlineShapes.AddPicture(FileName, ref LinkToFile, ref SaveWithDocument, ref Anchor);
//由于是本文档的第2张图,所以这里是InlineShapes[2]
wordDoc.Application.ActiveDocument.InlineShapes[2].Width = 50;//图片宽度
wordDoc.Application.ActiveDocument.InlineShapes[2].Height = 35;//图片高度
// 将图片设置为四周环绕型
MSWord.Shape s = wordDoc.Application.ActiveDocument.InlineShapes[2].ConvertToShape();
s.WrapFormat.Type = MSWord.WdWrapType.wdWrapSquare;

2、使用spire组件,代码如下:

string FileName = Environment.CurrentDirectory + "\\6.jpg";//图片所在路径
FileStream fileStream = new FileStream(FileName, FileMode.Open, FileAccess.Read);
BinaryReader binaryReader = new BinaryReader(fileStream);
byte[] imgbyte = binaryReader.ReadBytes((int)fileStream.Length);
DocPicture docimg = paragraph.AppendPicture(imgbyte);
docimg.Width = 750;
docimg.Height = 750 ;
docimg.VerticalPosition = 2;//图像停靠方式
docimg.TextWrappingStyle = DocWord.Documents.TextWrappingStyle.InFrontOfText;//图像文字环绕方式

参考文档

C#操作Word的超详细总结
用C#实现在Word文档中搜索文本
C#使用spire.doc对word文档表格进行数据填充(主要针对word插入图像)
Spire.Doc for .NET 中文教程
去除Spire.pdf生成时出现警告语Evaluation Warning
C#/VB.NET 用图片、表格替换 Word 文本

C#中,在Word文档中插入图片的方法是使用Microsoft.Office.Interop.Word库中的对象模型来实现。首先,我们需要加载Word模板文件,然后通过书签(Bookmark)定位到需要插入图片的位置,最后使用Selection对象的InlineShapes属性来添加图片。 以下是一个示例代码来演示在Word插入图片的方法: ```csharp using Microsoft.Office.Interop.Word; // 创建Word应用程序对象 Application app = new Application(); // 打开模板文件 Document doc = app.Documents.Open("D:\\Test.docx"); // 设置Word窗口可见 app.Visible = true; // 遍历所有书签 foreach (Bookmark bookmark in doc.Bookmarks) { if (bookmark.Name == "picture") { // 定位到书签位置 bookmark.Select(); // 获取当前选中位置的Selection对象 Selection selection = app.Selection; // 使用InlineShapes属性添加图片 selection.InlineShapes.AddPicture("D:\\Test.jpg"); } } // 保存文档 doc.SaveAs("E:\\Test.docx"); // 关闭Word应用程序 app.Quit(); ``` 在上述代码中,我们首先创建了一个Word应用程序对象,并打开了模板文件。然后,我们遍历所有的书签,当找到名为"picture"的书签时,我们使用Select方法将鼠标焦点定位到该书签位置,并通过app.Selection获取当前选中位置的Selection对象。最后,我们使用InlineShapes属性的AddPicture方法来添加图片。 请注意,上述代码仅为示例,实际使用时可能需要根据具体情况进行适当的修改。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值