首页 > 开发 > .Net > 正文

用.net操作word

2020-02-03 16:00:38
字体:
来源:转载
供稿:网友


要操作word,我们就需要word的对象库文件“msword.olb”(word 2000为msword9.olb),通常安装了office word后,你就可以在office安装目录的office10文件夹下面找到这个文件,当我们将这个文件引入到项目后,我们就可以在源码中使用各种操作函数来操作word。具体做法是打开菜单栏中的项目>添加引用>浏览,在打开的“选择组件”对话框中找到msword.olb后按确定即可引入此对象库文件,vs.net将会自动将 库文件转化为dll组件,这样我们只要在源码中创建该组件对象即可达到操作word的目的!

在cs代码文件中对命名空间的应用,如:using word;范例如下:

using system;
using system.drawing;
using system.collections;
using system.componentmodel;
using system.windows.forms;
using word;

namespace examsecure
{
///
/// itemtodoc 的摘要说明。
///
public class itemtodoc : system.windows.forms.form
{
object strfilename;
object nothing;
word.applicationclass mywordapp=new word.applicationclass();
word.document myworddoc;
string strcontent="";

private system.componentmodel.container components = null;

public itemtodoc()
{
//
// windows 窗体设计器支持所必需的
//
initializecomponent();

//
// todo: 在 initializecomponent 调用后添加任何构造函数代码
//
}
[stathread]
static void main()
{
system.windows.forms.application.run(new itemtodoc());
}
///
/// 清理所有正在使用的资源。
///
protected override void dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.dispose();
}
}
base.dispose( disposing );
}

#region windows form designer generated code
///
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
///
private void initializecomponent()
{
//
// itemtodoc
//
this.autoscalebasesize = new system.drawing.size(6, 14);
this.clientsize = new system.drawing.size(292, 273);
this.name = "itemtodoc";
this.text = "itemtodoc";
this.load += new system.eventhandler(this.itemtodoc_load);

}
#endregion
private void itemtodoc_load(object sender, system.eventargs e)
{
writefile();
}
private void writefile()
{

strfilename=system.windows.forms.application.startuppath+"//试题库【"+getrandomstring()+"】.doc";
object nothing=system.reflection.missing.value;
myworddoc=mywordapp.documents.add(ref nothing,ref nothing,ref nothing,ref nothing);

#region 将数据库中读取得数据写入到word文件中

strcontent="试题库/n/n/r";
writefile(strcontent);

strcontent="试题库";
writefile(strcontent);


#endregion

//将worddoc文档对象的内容保存为doc文档
myworddoc.saveas(ref strfilename,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文档对象
myworddoc.close(ref nothing, ref nothing, ref nothing);
//关闭wordapp组件对象
mywordapp.quit(ref nothing, ref nothing, ref nothing);
}

///
/// 获取一个随即字符串
///
///
private string getrandomstring()
{
datetime inow=datetime.now;
string strdate=inow.tostring("yyyymmddhhmmffff");

random ran=new random();
int iran=convert.toint32(10000*ran.nextdouble());
string strran=iran.tostring();
//位数不足则补0
int iranlen=strran.length;
for(int i=0;i<4-iranlen;i++)
{
strran="0"+strran;
}
return strdate+strran;
}

///
/// 将字符串写入到word文件中
///
/// 要写入的字符串
private void writefile(string str)
{
myworddoc.paragraphs.last.range.text=str;
}
}
}




发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表