|
[广告] Excel易用宝 - 提升Excel的操作效率 · Excel / WPS表格插件 ★ 免费下载 ★ ★ 使用帮助★
先简单介绍下AirScript,金山文档开发的,用于在线文档自动化的脚本,使用Java Script编程语言。
AirScript提供了一个脚本令牌,用于外部应用读写授权的个人在线文档,官方文档看这里接口说明 | AirScript文档 (wps.cn)
大致思路:用VBA将工作表数据转换成JS数组格式[[],[]],通过POST方法将数据传给金山文档AirScript脚本,脚本把收到的数据处理后写入金山文档的数据表。
VBA代码,注意替换自己的API Token,方法看上面的文档,很简单
- Option Explicit
- Sub main()
- Dim arr
- Dim t$, postData$, strHtml$
- Dim http As Object
- Set http = CreateObject("Msxml2.XMLHTTP")
- arr = Range("A1:D5").Value
- t = transArr(arr)
- postData = "{""Context"":{""argv"":{""js"":" & t & "}}}"
- http.Open "POST", "https://www.kdocs.cn/api/v3/ide/file/cdGI8YQoHohP/script/V2-7vDppjz7TVABraD2cJH9Kw/sync_task", False
- http.setRequestHeader "Content-Type", "application/json"
- http.setRequestHeader "AirScript-Token", "你的令牌"
- http.send (postData)
- strHtml = http.responseText
- Set http = Nothing
- End Sub
- Function transArr(arr) '把VBA数组转化为格式化的JS数组字符串
- Dim t$, s$
- Dim i&, k&
- Dim brr(), crr()
- ReDim brr(1 To UBound(arr, 2))
- ReDim crr(1 To UBound(arr, 1))
- For i = 1 To UBound(arr, 1)
- For k = 1 To UBound(arr, 2)
- brr(k) = Chr(34) & IIf(IsDate(arr(i, k)), Format(arr(i, k), "yyyy/mm/dd"), arr(i, k)) & Chr(34)
- Next
- s = Join(brr, ",")
- s = "[" & s & "]"
- crr(i) = s
- Next
- t = Join(crr, ",")
- transArr = "[" & t & "]"
- End Function
复制代码 AirScript代码
- const arr=Context.argv.js; //接收
- let resArr=[];
- const dsh1=Application.Sheets('数据表');
- const dsh2=Application.Sheets('写入测试');
- const res=Array.from(fetchAllRecords(dsh1));
- for(let i=1;i<arr.length;i++){
- let obj={fields:{}};
- obj.fields[arr[0][0]]=arr[i][0];
- obj.fields[arr[0][1]]=Number(arr[i][1]);
- obj.fields[arr[0][2]]=arr[i][2];
- let t=arr[i][3];
- let temp=res.find(x=>x.fields.文本==t);
- obj.fields[arr[0][3]]={recordIds:[temp.id]};
- resArr.push(obj);
- };
- console.log(resArr)
- dsh2.Record.CreateRecords({
- Records:resArr
- });
- function fetchAllRecords(dsh) {
- let all = []
- let offset = null;
- while (all.length === 0 || offset) {
- let records = dsh.Record.GetRecords({
- Offset: offset
- })
- offset = records.offset
- all = all.concat(records.records)
- };
- return all;
- };
复制代码 金山文档链接:【金山文档】 脚本令牌
https://kdocs.cn/l/cdGI8YQoHohP
金山文档我给了所有人编辑权限,但请不要删除表,修改表的字段。否则别人就无法测试了
|
评分
-
2
查看全部评分
-
|