62,041
社区成员
发帖
与我相关
我的任务
分享
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using Microsoft.Office.Interop.Word;
using System.Web;
using System.IO;
using System.Web.UI.WebControls;
using System.Web.UI;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
//string path = "I:\\Filldoc\\download"; //路径
//string path = Server.MapPath("~/") + "";
//string templatePath = "E:\\设计报告\\SH08J7G01.docx";
string templatePath = Server.MapPath("~/DesignRp/") + "SH08J7G01.docx";//该文件存在
WordOp wop = new WordOp();
wop.OpenTempelte(templatePath);
wop.FillLable("D", "A970");
//wop.FillLable("usr_name", "测试");
//wop.SaveAs("E:\\设计报告\\savetest.docx",true);
wop.Quit();
}
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();
}
}
class BR : Control
{
protected override void Render(HtmlTextWriter writer)
{
writer.Write("<br />");
}
}
}