代码改变世界

用JavaScript在Word文档插入内容

2010-04-20 15:33  .金楽.  阅读(870)  评论(0编辑  收藏  举报
在工作中,经常遇到在Word文档中某特定位置写入内容,同事之前的做法是在Word文档需要写内容的地方做一个标志(插入一段作为表示的文字),然后在代码中执行宏进行替换。这个方法有个不好的地方就是占用服务器资源,而且进程必须要以管理员权限的帐号启动,否则速度特别慢。为了解决这个问题,我决定用JavaScript实现。今天写了一个脚本,测试了一下,觉得速度挺快的,发出来给需要的朋友参考:
//功能:在Word文档插入文字和图片,shimin.huaug
//参数一:insertType 插入内容类型,0为图片,1为文字
//参数二:filePath Word文档的路径
//参数三:tagArray Word文档中插入内容的定位标志
//参数四:insertArray 插入内容,可以为文字或图片的路径
function WordInsert(insertType,filePath,tagArray,insertArray)
{
    //ShowWaitingPrompt();
    if(tagArray.length != insertArray.length)
    {
        alert('参数数组长度不相同!');
        return;
    }
    
    var arrayLength = tagArray.length;
    var wordApp = null;
    
    try
    {
        wordApp = new ActiveXObject('Word.Application');
    }
    catch(e)
    {
        alert(e+', 原因分析: 浏览器安全级别较高导致不能创建Word对象或者客户端没有安装Word软件');
  return;
    }
    
    var wordDoc = wordApp.Documents.Open(filePath);
    wordDoc.Activate();
    var Selection = wordApp.Selection;
    Selection.Find.Replacement.Text = '';
    Selection.Find.Forward = true;
    Selection.Find.Wrap = 1;
    Selection.Find.Format = false;
    Selection.Find.MatchCase = false;
    Selection.Find.MatchWholeWord = false;
    Selection.Find.MatchByte = true;
    Selection.Find.MatchWildcards = false;
    Selection.Find.MatchSoundsLike = false;
    Selection.Find.MatchAllWordForms = false;
    
    for(i = 0; i < arrayLength; i++)
    {  
        Selection.Find.ClearFormatting();    
        Selection.Find.Text = tagArray[i];
        while(Selection.Find.Execute())
        {
            if(insertType == 0)
            {
                Selection.InlineShapes.AddPicture(insertArray[i], false, true);
            }
            else if(insertType == 1)
            {
                Selection.TypeText(insertArray[i])
            }
            else
            {
                alert("没有定义该插入内容类型!")
                return;
            }
        }
    }
    
    //CloseWaitingPrompt();
    
    //wordDoc.PrintOut();
    wordApp.visible = true;
}