自定义函数 JSA_A_UINT8ARRAYTOUTF8TOSTRING 将UTF-8解码为字符串
function JSA_A_UINT8ARRAYTOUTF8TOSTRING(uint8Array, format) { // Uint8Array 转 UTF8 转 Unicode 转 String
//表格中使用函数,参数留空时,默认值处理
uint8Array = uint8Array === -2147352572 ? undefined : uint8Array;
format = format === -2147352572 ? undefined : format;
// 参数验证和默认值处理
uint8Array = (Array.isArray(uint8Array.valueOf()) || (uint8Array instanceof Uint8Array)) ? Array.from(uint8Array.valueOf()).flat(Infinity).filter(v => v !== null && v !== undefined && v !== "") : [uint8Array.valueOf()].filter(v => v !== null && v !== undefined && v !== "");
format = (format || 'dec').toLowerCase();
// 验证参数有效性
if (uint8Array.length === 0) {
return "#N/A";
}
if (!['bin', 'hex', 'dec'].includes(format)) {
return "#N/A";
}
const percentEncoded = uint8Array.map(x => {
switch (format) {
case 'bin':
return '%' + parseInt(x, 2).toString(16).padStart(2, '0');
case 'hex':
return '%' + x.padStart(2, '0');
case 'dec':
return '%' + x.toString(16).padStart(2, '0');
}
}).join('');
if (percentEncoded === undefined || percentEncoded === "") {
return "#N/A";
}
return decodeURIComponent(percentEncoded);
}插入函数对话框、函数参数对话框:
加载宏文件function Workbook_Open(){}中添加以下代码。
Application.MacroOptions("JSA_A_UINT8ARRAYTOUTF8TOSTRING", "将UTF-8编码的Uint8Array解码为字符串。", undefined, undefined, undefined, undefined, 14, undefined, undefined, undefined, ['UTF-8编码的Uint8Array,也可以是单行或多行数组。', '输入字节的格式。"dec":十进制字节值(默认),"hex":十六进制字节值,"bin":二进制字节值。']);