C#操作Office.word(二)

在上一篇文章"C#操作Office.word(一)"中我们讲述了如何使用VS2010引用COM中Miscrosoft Word 14.0 Object Library实现创建文档,而这篇文章将讲述如何添加表格和图片,因为我在C#联系数据库做销售系统中需要打印表单,,我想以图表形式显示在word中,同时生成相应的饼状图或柱状图,所以才有查阅了相关资料,完成文章,供大家分享。其中使用openFileDialog控件也是希望大家学习了解下。

一. 界面设置

在界面上增加一个按钮,点击这个按钮,就能把一个表格和一幅图片插入到word中。为了简单,这里我们把表格和图片的设置直接写在源代码中。

二. 源代码

1.引用空间

//引用word对象类库和命名空间
using MSWord = Microsoft.Office.Interop.Word;
using System.IO;
using System.Reflection;

2.添加外部变量

object path;                      //声明文件路径变量
MSWord.Application wordApp;       //声明word应用程序变量
MSWord.Document worddoc;          //声明word文档变量    

3.插入表格和图片

点击"创建"按钮在生成的函数create_Click(object sender, EventArgs e)中添加实现向word中插入表格和图片的代码,如下:

private void btnImg_Click(object sender, EventArgs e)
{
	//表格的行数和列数
	Int32 rowNum = 4;
	Int32 colNum = 4;
	//图片的路径
	string picturePath = "E:\hand.bmp";

	//初始化变量   
	object Nothing = Missing.Value; //表示缺少的值   
	//object format = MSWord.WdSaveFormat.wdFormatDocumentDefault; //格式docx
	object format = MSWord.WdSaveFormat.wdFormatDocument;           //格式doc
	wordApp = new MSWord.ApplicationClass();                     //声明一个wordAPP对象   
	worddoc = wordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);
	//定义word文档中表格   
	MSWord.Table table = worddoc.Tables.Add(wordApp.Selection.Range,
		rowNum, colNum,
		ref Nothing, ref Nothing);                                //定义一个表格对象 

	table.Borders.Enable = 1;                                    //默认表格没有边框   
	//填充表格中内容   
	for (int i = 1; i <= rowNum; i++)    //string转换int型   
	{
		for (int j = 1; j <= colNum; j++)
		{
			table.Cell(i, j).Range.Text = "(" + i + "行," + j + "列)";
		}
	}
	//定义插入图片是否为外部链接   
	Object linktofile = true;
	Object savedocument = true;
	Object range = worddoc.Paragraphs.Last.Range;                //定义图片插入word位置  

	worddoc.InlineShapes.AddPicture(picturePath, ref linktofile, ref savedocument, ref range);
	//保存文档   
	path = "E:" + "\" + "hand";          //设置文件保存路劲

	worddoc.SaveAs(ref path, ref format, 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);  //关闭worddoc文档对象   
	wordApp.Quit(ref Nothing, ref Nothing, ref Nothing);   //关闭wordApp组对象 
	
	MessageBox.Show("文档创建成功!"); 

}//btnCreate_Click

三. 运行结果

点击“创建”后,它会在E盘下创建一个hand.doc的word文档,同时填写内容如下图所示:

四. 补充知识

其中在插入图片中我使用了一个InlineShapes.AddPicture函数,它相应的使用方法如下图所示:

原文地址:https://www.cnblogs.com/stemon/p/4617550.html