Power Automate触发Excel脚本报错:Text Encoder未定义
解决Power Automate触发Excel Script时"Text Encoder not defined"错误
问题背景
你的Excel Script在Excel客户端/网页端运行正常,但通过Power Automate触发时抛出Text Encoder not defined错误,核心原因是代码中依赖的TextEncoder是浏览器环境的原生API,而Power Automate执行Excel Script的后端环境未内置该API。
解决方案
替换TextEncoder.encode为自定义的字符串转UTF-8编码Uint8Array的函数,确保在所有执行环境中兼容。以下是修改后的完整代码:
async function main(workbook: ExcelScript.Workbook) { let sheet = workbook.getWorksheet("Sheet1"); let usedRange = sheet.getUsedRange(); let lastRow = usedRange.getLastRow().getRowIndex(); lastRow = lastRow + 1; let range = sheet.getRange("B2:B" + lastRow); let values = range.getValues(); // 自定义UTF-8编码函数,替代浏览器内置TextEncoder function stringToUtf8Bytes(str: string): Uint8Array { const bytes: number[] = []; for (let i = 0; i < str.length; i++) { let charCode = str.charCodeAt(i); // 单字节字符(ASCII) if (charCode < 0x80) { bytes.push(charCode); } // 双字节字符 else if (charCode < 0x800) { bytes.push(0xc0 | (charCode >> 6), 0x80 | (charCode & 0x3f)); } // 三字节字符(排除代理对范围) else if (charCode < 0xd800 || charCode >= 0xe000) { bytes.push(0xe0 | (charCode >> 12), 0x80 | ((charCode >> 6) & 0x3f), 0x80 | (charCode & 0x3f)); } // 四字节字符(处理UTF-16代理对) else { i++; charCode = 0x10000 + (((charCode & 0x3ff) << 10) | (str.charCodeAt(i) & 0x3ff)); bytes.push(0xf0 | (charCode >> 18), 0x80 | ((charCode >> 12) & 0x3f), 0x80 | ((charCode >> 6) & 0x3f), 0x80 | (charCode & 0x3f)); } } return new Uint8Array(bytes); } let hashedValues = await Promise.all(values.map(async (value) => { // 处理空单元格,避免传入undefined导致编码失败 const msgBuffer = stringToUtf8Bytes(value[0] || ''); const hashBuffer = await crypto.subtle.digest('SHA-256', msgBuffer); const hashArray = Array.from(new Uint8Array(hashBuffer)); const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join(''); return [hashHex]; })); range.setValues(hashedValues); }
修改说明
- 自定义编码函数:
stringToUtf8Bytes完全实现了TextEncoder.encode的UTF-8编码逻辑,兼容所有支持TypeScript的执行环境。 - 空值处理:增加
value[0] || ''判断,避免空单元格传入undefined导致编码错误。
内容的提问来源于stack exchange,提问作者Kah Sheung CHAN
相关产品推荐
相关产品推荐

