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

来源:爱站网时间:2019-09-07编辑:网友分享
我们在开发asp.net项目时,会遇到导出文件的情况,如将数据从datagrid导出到excel文件,这个时候我们该怎么做呢?下面爱站技术频道小编给大家介绍asp.net下将页面内容导入到word模板中的方法。

我们在开发asp.net项目时,会遇到导出文件的情况,如将数据从datagrid导出到excel文件,这个时候我们该怎么做呢?下面爱站技术频道小编给大家介绍asp.net下将页面内容导入到word模板中的方法。

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,在需要使用的页面后台调用既可,举例如下:

 

 

上面就是对爱站技术频道小编给大家带来的asp.net下将页面内容导入到word模板中的方法,请各位认真阅读,如果有什么疑惑的地方可以提出来,爱站技术频道小编将会认真解答,谢谢各位的阅读。 

上一篇:asp.net 常用字符串处理方法

下一篇:GridView导出Excel的实现案例

您可能感兴趣的文章

相关阅读

热门软件源码

最新软件源码下载