首先,在网上搜了一圈都没有发现有什么免费的框架能够直接操作Word的。有的话大概就是QT,Telerik这样子的收费的。
然后呢,Word是巨硬出的东西,那么同样是巨硬出品的C#应该是支持的。于是就去百度了一圈C#操作Word,果然还是有这方面的资料的。
以下为操作:
- 首先需要安装Office。因为需要使用到Office的COM组件。
- 之后新建C#的工程,随便什么工程C#的就好,控制台程序都行。
- 导入COM组件。Microsoft Word 12.0 Library。导入之后就能够使用
using Microsoft.Office.Interop.Word;
开始写代码。
- 新建一个Word的进程。
虽然是使用了Office的COM组件,但是我们还是不能够直接操作word文件(doc/docx)。是通过一个Word的进程去操作word文件的,而我们支持操作这个进程而已。运行程序的时候,打开任务管理器,查看进程,就能够看到新建的word进程
使用下面的代码就能够建立Word进程
```Cs
Microsoft.Office.Interop.Word.Application WordApp = new Microsoft.Office.Interop.Word.Application();
```
如果是想看着Word界面里面神一样的手速操作的话,你可以使用这一句来显示Word界面
```Cs
WordApp.Visible = true;
```
- 打开一个新的Word空白窗口
既然新建了一个进程,那么我们开始就使用这个进程开始操作吧
使用下面的代码能够得到一个空的文档()相当于点击双击启动Word。
Object oMissing = System.Reflection.Missing.Value;
Microsoft.Office.Interop.Word._Document WordDoc = WordApp.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing);
- 保存Word文档
我们已经新建好了文档,那么我们就来把这个文档保存一下。
使用下面的代码能够保存文档。
string fileName = "这里是你要保存的文件路径";
object filename = fileName;
WordDoc.SaveAs(ref filename, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
//关闭当前文档
WordDoc.Close(ref oMissing, ref oMissing, ref oMissing);
//关闭Word进程
WordApp.Quit(ref oMissing, ref oMissing, ref oMissing);
好了,第一步差不多就做到这里了。之后我们再讲如何操作Word的内容。
网友评论