word 文档操作

word文档操作

 

0、文档操作之前引用声明部分

using Microsoft.Office.Core;
using Microsoft.Office.Interop;
using Word = Microsoft.Office.Interop.Word;

 

 Object Nothing = System.Reflection.Missing.Value;

 object filename = "D:\\aa.docx";
 Word._Document oDoc = null;
 Word.Document WordDoc = null;
 Word.Application WordApp = null;

1.创建word文档

Word.Application WordApp = new Word.ApplicationClass();
Word.Document WordDoc = WordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);

2、打开word文档

Word._Application oword = new Word.Application();

//属性,可以根据需要设

object readOnly = false;
oword.Visible = true;
oDoc = oword.Documents.Open(ref filename, ref Nothing, ref readOnly, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing);

//打印文档中的文字部分
Console.WriteLine(oDoc.Content.Text as string );

//在文档中最前面插入内容

Word.Range p_range = oDoc.Paragraphs[1].Range;
p_range.Text = "本句话将加在文档内容最前面";

//在文档最后面加内容

oDoc.Paragraphs.Last.Range.Text = "该句话将加在文档内容最后面";

//激活改word文档,使其显示出来

 oDoc.Activate();

 

3、保存和关闭word文档

//保存文档

WordDoc.SaveAs(ref filename, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing);

//关闭文档
WordDoc.Close(ref Nothing, ref Nothing, ref Nothing);

 

注意:操作word文档时要引用自己正在用的word文件的MSWORD.OLB因为不同版本里的word文件的MSWORD.OLB不相同。该文件一般都在word文件的安装文件里。本文上传的是07版word的MSWORD.OLB

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值