在实际开发中,会遇到在WORD提供的模板中,插入特定的信息。如下模板:
JS操作WORD测试
姓名 | ${name} | 性别 | ${sex} | 民族 | ${mz} | ${photo} |
住址 | ${address} | |||||
${name} | ${name} | ${name} | ||||
${name} | ${name} | ${name} | ||||
${name} | ${name} | ${name} |
生成结果:
JS操作WORD测试
姓名 | 涛哥 | 性别 | 男 | 民族 | 汉 |
|
住址 | 地球3号 | |||||
涛哥 | 涛哥 | 涛哥 | ||||
涛哥 | 涛哥 | 涛哥 | ||||
涛哥 | 涛哥 | 涛哥 |
代码如下:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=gb2312">
<title>JS test</title>
</head>
<body>
<button id='testBtn' οnclick='onTest()'>TEST</button>
</body>
<script>
function onTest()
{
var po = {};
po.name = '涛哥';
po.sex = '男';
po.mz = '汉';
po.address = '地球3号';
po.template = 'http://localhost:9090/log/jsword/jstest.docx';
po.photo = 'https://i-blog.csdnimg.cn/blog_migrate/e1dde8a9035ab3675c5d29d11bf7a4b9.gif';
exportWord(po);
}
function exportWord(po)
{
var wApp = new ActiveXObject("Word.Application");
wApp.Application.Visible = true;
var doc = wApp.Documents.Open(po.template);
var fnd = doc.Content.Find;
var bOK = fnd.Execute('${name}', true, true, false, false, false, true, 0 , false, po.name, 2);
bOK = fnd.Execute('${sex}', true, true, false, false, false, true, 0 , false, po.sex, 2);
bOK = fnd.Execute('${mz}', true, true, false, false, false, true, 0 , false, po.mz, 2);
bOK = fnd.Execute('${address}', true, true, false, false, false, true, 0 , false, po.address, 2);
var cell = doc.Tables(1).Cell(1,7);
cell.Range.InlineShapes.AddPicture(po.photo);
//Execute('${name}', true, true, false, false, false, true, WdFindWrap , false, name, wdReplaceAll, MatchKashida, MatchDiacritics, MatchAlefHamza, MatchControl, MatchPrefix, MatchSuffix, MatchPhrase, IgnoreSpace, IgnorePunct);
}
</script>
</html>