宏和js实现word内容替换

通过宏和ActiveXObject来控制 word操作,包括文字替换、文字替换为图片

  1. 使用ActiveXObject前需要配置Internet属性
    宏和js实现word内容替换_第1张图片
    宏和js实现word内容替换_第2张图片
  2. 通过宏来替换文字、文字替换图片
    2.1 文字替换为图片
For i = 1 To ActiveDocument.Paragraphs.Count
mypic = ActiveDocument.Paragraphs(i).Range.Text
If InStr(mypic,”picture”) > 0 Then
        ActiveDocument.Paragraphs(i).Range.Select
        Selection.InlineShapes.AddPicture filename:=”C:/1.jpg”, LinkToFile:=False, SaveWithDocument:=True
        Selection.InsertBefore (Chr(10))      '换行    Chr(13)  回车
    End If
Next

2.2 文字替换

Set myRange = ActiveDocument.Content
With myRange.Find
.Text = “原文字”
    .Forward = True
    .Wrap = wdFindStop
    .Execute
End With
With myRange
    Do While .Find.Found = True
        .Text = “新文字”
        .Find.Execute
    Loop
End With

2.3 读取文件,截取 warnCategory= **%1end 字符串

Public CookieFile As String
Public LotusDocID As String
CookieFile = CookieFile + "Cookie.txt"
Dim mylog
Set mylog = CreateObject("Scripting.FileSystemObject")
If (mylog.FileExists(CookieFile)) Then
Open CookieFile For Input As #1
    Input #1, StrCookie
Close #1
Dim MyPosEnd As Integer
MyPosEnd = InStr(1, StrCookie, "%1end") - 1
LotusDocID = Left(StrCookie, MyPosEnd)
LotusDocID = Right(LotusDocID, MyPosEnd - InStr(LotusDocID, "warnCategory=") - 12)

2.4 获取当前文件路径

Dim wordPath
wordPath = ActiveDocument.Path
Dim sourceArr
sourceArr = Split(wordPath, Application.PathSeparator)
For subi = 0 To UBound(sourceArr) 
    CookieFile = CookieFile + sourceArr(subi) + Application.PathSeparator
Next subi
  1. 通过ActiveXObject 来替换文字、文字替换图片
    3.1 创建文件打开
var wordApp = new ActiveXObject("Word.Application");
wordApp.Visible = false;
var redHeadFileName=new UUID().createUUID()+'.doc';
var docPath =baseUrl+ "/attachment/downloadByNewFileName.do?attId="+attId+"&newFileName="+redHeadFileName;
var d = new word({
	srcurl : docPath,
	destfile : redHeadFileName,
	myword : wordApp,
	docVisible : false
});
d.build();
d.open();

3.2 文字替换

var selection = wordApp.Selection;
selection.Find.Text = "¥¥context";
selection.Find.wrap = 1;
while (selection.Find.Execute()) {
   selection.paste();
}
selection.Find.Text="¥¥warnCategory";
selection.Find.wrap=1;
while(selection.Find.Execute()){
selection.TypeText(new);
}
wordApp.Visible = true;
wordApp.Application.Activate();

发现的问题,selection.TypeText(“”); 不会替换内容
3.3 文字替换图片

var count = wordApp.documents(1).paragraphs.count;
var mypic = "";
for(var i = 1;i<=count ; i++){
    var mypic = wordApp.documents(1).paragraphs(i).range.text;
    if(mypic.indexOf("¥¥picture") > -1){
        wordApp.documents(1).paragraphs(i).range.select();
        wordApp.Selection.InlineShapes.AddPicture("E:\\20190819\\1.gif");
        wordApp.Selection.InsertBefore ("\n\r");
    }
}
  1. 如果是Excel , ActiveXObject 怎么打开
var excelApp = new ActiveXObject("Excel.Application");
var d = new excel({
    srcurl : docPath,
    destfile : redHeadFileName,
    myword : excelApp,
    docVisible : false
});
d.build();
var oWB = d.open();   //Open方法修改为 myword.Workbooks.Open(desturl)
oWB.worksheets(1).select();
var workSheet = oWB.ActiveSheet;
workSheet.Cells(2,2).Value = "100";
workSheet.Cells(3,2).Value = "100";
excelApp.Application.Visible = true;
  1. 遇到问题
    5.1 被呼叫方拒绝接收呼叫
    打开window任务管理器,发现Word进程还在,说明资源没有释放
    查找文档,确保关闭 new的ActiveXObject
  2. 相关js
/**
 * config = {srcurl,destfile,isnew,uploadpath}
 * srcurl: 远程服务器文件 e.g. http://128.96.172.238:9080/aaa/upload/aaa.doc
 * destfile: 本地的文件名称 e.g. zhwm.doc
 * isnew: 是本地新建,还是远程下载
 * uploadpath: 上传到服务器的doc文件路径 e.g.  /tomcat6.0/webapps/aaa/upload/ 
 * upload_target_url:上传doc文件到服务器的jsp
 */

$(document).ready(function(){
	$("head").append("");
});
word = function(config) {
	var myword, fso ,mydoc,xml_dom, ado_stream;
	var myinterval,  srcurl, uploadpath, desturl,destfile,upload_target_url;
	var destDir=downContextPath;
    var docVisible=true;
	
	
	function init(){
		fso = new ActiveXObject("Scripting.FileSystemObject");
	}
    function InitAjax() {
        var ajax;
        if (window.ActiveXObject) {
            var versions = ['Microsoft.XMLHTTP', 'MSXML.XMLHTTP', 'Microsoft.XMLHTTP', 'Msxml2.XMLHTTP.7.0', 'Msxml2.XMLHTTP.6.0', 'Msxml2.XMLHTTP.5.0', 'Msxml2.XMLHTTP.4.0', 'MSXML2.XMLHTTP.3.0', 'MSXML2.XMLHTTP'];
            for (var i = 0; i < versions.length; i++) {
                try {
                    ajax = new ActiveXObject(versions[i]);
                    if (ajax) {
                        return ajax;
                    }
                } catch (e) {
                }
            }
        } else if (window.XMLHttpRequest) {
            ajax = new XMLHttpRequest();
        }
        return ajax;
    }
    var ajaxWord;
    function getFileByServer(srcUrl) {
        ajaxWord = InitAjax();
        ajaxWord.onreadystatechange = getReady; // 回调函数
        ajaxWord.open('post', srcUrl, false);
        ajaxWord.send();
    }
	this.close = function(){
        if(null!=mydoc){
		  mydoc.close();
		  mydoc = null;
        }
        if(myword){
          myword.quit();
          myword = null;
        }

	}
	this.build = function() {
		init();
	    if (typeof config.srcurl == 'undefined') {
			alert('请指定参数srcurl');
		}else {
			srcurl = config.srcurl;
		}
		if(typeof config.destfile == 'undefined')
			alert('请指定参数destfile');
		else destfile = config.destfile;

        if(!(typeof config.destfile == 'undefined')){
            docVisible=config.docVisible;
        }
		desturl = destDir + destfile;
		myword = config.myword;

		createLocalDir();
        getFileByServer(srcurl);
	}
	
	function createLocalDir(){
		if(!fso.FolderExists(destDir)){
			fso.CreateFolder(destDir);
		}
		if (fso.FileExists(desturl)) {
			fso.DeleteFile(desturl);
		}
		fso = null;
	}
    this.open=function openWord(){
        fso = new ActiveXObject("Scripting.FileSystemObject");
        // 判断 文件是否存在
        if(!fso.FileExists(desturl)){
            alert("目标文件不存在,打开失败");
            fso.close();
            this.close();
            return null;
        }
		myword.visible = docVisible;
        mydoc= myword.Documents.Open(desturl);
        return mydoc;
	}
    function getReady(func) {
        if (ajaxWord.readyState == 4) {
            if (ajaxWord.status == 200) {
                saveFile(desturl);
                return true;
            }else {
                return false;
            }
        } else{
            return false;
        }
    }

    function saveFile(tofile) {
        var objStream;
        var file;
        file = ajaxWord.responseBody;
        objStream = new ActiveXObject("ADODB.Stream");
        objStream.Mode = 3 ;           //读写
        objStream.Type = 1;            //文本
        objStream.open();
        objStream.write(file);
        objStream.SaveToFile(tofile);
        objStream.close();
        objStream=null;

    }
}

excel = function(config) {
    var myword, fso ,mydoc,xml_dom, ado_stream;
    var myinterval,  srcurl, uploadpath, desturl,destfile,upload_target_url;
    var destDir=downContextPath;
    var docVisible=true;


    function init(){
        fso = new ActiveXObject("Scripting.FileSystemObject");
    }
    function InitAjax() {
        var ajax;
        if (window.ActiveXObject) {
            var versions = ['Microsoft.XMLHTTP', 'MSXML.XMLHTTP', 'Microsoft.XMLHTTP', 'Msxml2.XMLHTTP.7.0', 'Msxml2.XMLHTTP.6.0', 'Msxml2.XMLHTTP.5.0', 'Msxml2.XMLHTTP.4.0', 'MSXML2.XMLHTTP.3.0', 'MSXML2.XMLHTTP'];
            for (var i = 0; i < versions.length; i++) {
                try {
                    ajax = new ActiveXObject(versions[i]);
                    if (ajax) {
                        return ajax;
                    }
                } catch (e) {
                }
            }
        } else if (window.XMLHttpRequest) {
            ajax = new XMLHttpRequest();
        }
        return ajax;
    }
    var ajaxWord;
    function getFileByServer(srcUrl) {
        ajaxWord = InitAjax();
        ajaxWord.onreadystatechange = getReady; // 回调函数
        ajaxWord.open('post', srcUrl, false);
        ajaxWord.send();
    }
    this.close = function(){
        if(null!=mydoc){
            mydoc.close();
            mydoc = null;
        }
        if(myword){
            myword.quit();
            myword = null;
        }
    }
    this.build = function() {
        init();
        if (typeof config.srcurl == 'undefined') {
            alert('请指定参数srcurl');
        }else {
            srcurl = config.srcurl;
        }
        if(typeof config.destfile == 'undefined')
            alert('请指定参数destfile');
        else destfile = config.destfile;

        if(!(typeof config.destfile == 'undefined')){
            docVisible=config.docVisible;
        }
        desturl = destDir + destfile;
        myword = config.myword;

        createLocalDir();
        getFileByServer(srcurl);
    }

    function createLocalDir(){
        if(!fso.FolderExists(destDir)){
            fso.CreateFolder(destDir);
        }
        if (fso.FileExists(desturl)) {
            fso.DeleteFile(desturl);
        }
        fso = null;
    }
    this.open=function openWord(){
        fso = new ActiveXObject("Scripting.FileSystemObject");
        // 判断 文件是否存在
        if(!fso.FileExists(desturl)){
            alert("目标文件不存在,打开失败");
            fso.close();
            this.close();
            return null;
        }
        myword.visible = docVisible;
        mydoc= myword.Workbooks.Open(desturl);
        return mydoc;
    }
    function getReady(func) {
        if (ajaxWord.readyState == 4) {
            if (ajaxWord.status == 200) {
                saveFile(desturl);
                return true;
            }else {
                return false;
            }
        } else{
            return false;
        }
    }

    function saveFile(tofile) {
        var objStream;
        var file;
        file = ajaxWord.responseBody;
        objStream = new ActiveXObject("ADODB.Stream");
        objStream.Type = 1;
        objStream.open();
        objStream.write(file);
        objStream.SaveToFile(tofile);
        objStream.close();
        objStream=null;

    }
}

//根据标签和元素id替换相关值
function  replace(wordApp,label,value){
	  var selection = wordApp.Selection;
		// 替换值
      selection.Find.Text=label;
      selection.Find.wrap=1;
      while(selection.Find.Execute()){
        selection.TypeText($("#"+value).val());  // 设置值
        
      }
}

//根据标签和元素id替换相关值
function  replace2(wordApp,label,value){
	  var selection = wordApp.Selection;
	  // 替换值
      selection.Find.Text=label;
      selection.Find.wrap=1;
      while(selection.Find.Execute()){
        selection.TypeText(value);  // 设置值
        
      }
} 
// 正文下载的目录
var downContextPath="c:/ccbplmis_temp/";
// 正文上载文件的目录
var upContextPath="c:/ccbplmis/";

// 正文上传url
var baseUrl = "http://"+document.location.host+"/plmis";  

// 合成格式  word 蓝色 颜色编码
var buleColorCode=16724787;
//合成格式  word 黄色 颜色编码
var yellowColorCode=6553085;
//合成格式  word 橙色  颜色编码
var orangeyColorCode=3652077;
//合成格式  word 红色 颜色编码
var redColorCode=3034366;

你可能感兴趣的:(宏和js实现word内容替换)