欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

asp.net下将页面内容导入到word模板中的方法

程序员文章站 2024-03-08 11:29:22
1,新建word模版,方法是找需要用程序填充的word文档,在需要输入的地方用"书签"(插入-->书签-->输入id-->ok)标记后保存既可. 2,在w...
1,新建word模版,方法是找需要用程序填充的word文档,在需要输入的地方用"书签"(插入-->书签-->输入id-->ok)标记后保存既可.
2,在word模版上修改安全添加everyone 可读,以防文件无法打开.
3,在工程里添加"引用"找到"microsoft word 10.0 object library"或"microsoft word 11.0 object library"点确定.
4,新建类叫wordop.cs 意思是操作word的类.
内容如下:
复制代码 代码如下:

using system;
using system.web.security;
using microsoft.office.interop.word;
using system.io;
/// <summary>
/// word 的摘要说明
/// </summary>
public class wordop
{
public wordop()
{
//
// todo: 在此处添加构造函数逻辑
//
}
private applicationclass wordapp ;
private document worddoc;
private static bool isopened=false;//判断word模版是否被占用
public void saveas(string strfilename,bool isreplace)
{
if (isreplace && file.exists(strfilename))
{
file.delete(strfilename);
}
object missing = type.missing;
object filename = strfilename;
worddoc.saveas(ref filename, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
}
//定义一个word.application 对象
public void activewordapp()
{
wordapp = new applicationclass();
}
public void quit()
{
object missing = system.reflection.missing.value;
wordapp.application.quit(ref missing, ref missing, ref missing);
isopened = false;
}
//基于模版新建word文件
public void opentempelte(string strtemppath)
{
object missing = type.missing;
//object missing = system.reflection.missing.value;
activewordapp();
wordapp.visible = false;
object otemplate = (object)strtemppath;
try
{
while (isopened)
{
system.threading.thread.sleep(500);
}
worddoc = wordapp.documents.add(ref otemplate, ref missing, ref missing, ref missing);
isopened = true;
worddoc.activate();
}
catch (exception ex)
{
quit();
isopened = false;
throw new exception(ex.message);
}
}
public void filllable(string labelid,string content)
{
//打开word模版
// opentempelte(tempname); //对labelid的标签进行填充内容content,即函件题目项
object bkmc = labelid;
if (wordapp.activedocument.bookmarks.exists(labelid) == true)
{
wordapp.activedocument.bookmarks.get_item(ref bkmc).select();
}
wordapp.selection.typetext(content);
//saveas(saveasfilename);
//quit();
}
}

5,在需要使用的页面后台调用既可,举例如下:
复制代码 代码如下:

string path = server.mappath("download");
string templatepath = path + "file://downloadczql.doc/";
wordop wop = new wordop();
wop.opentempelte(templatepath);
wop.filllable("id", "1");
wop.filllable("usr_name", "测试");
wop.saveas(path + "file://savetest.doc",true/);
wop.quit();
response.redirect(@"/download/savetest.doc");//做个跳转用于下载.