跳到主要内容

查找替换

信息

支持在指定列中查找并替换指定的文本

实际效果

find-and-replace

源代码

const findText = await input.textAsync('请输入想查找的文本:');
const replaceText = await input.textAsync('想替换查找文本为:');

// 需要通过 Space API 获取当前激活的表格,并作为一个参数传入到 input.fieldAsync
const datasheet = await space.getActiveDatasheetAsync();
const field = await input.fieldAsync("请选择想要查找的维格列名", datasheet);
// 获取维格列的 id
const fieldId = field.id;

const records = await datasheet.getRecordsAsync();
const finalData = [];

// 遍历 records
for (let record of records) {
const recordId = record.id;
// 获取 record 指定 field 的数据为 cellValue
const cellValue = record.getCellValueString(fieldId);

// 如果获取的数据为空,则跳出此次循环,直接执行下一次
if (cellValue == null) continue;

// 替换 cellValue 中的 findText 为 replaceText,并使用新的变量——newCellValue
const newCellValue = cellValue.replaceAll(findText, replaceText);
// 判断替换前的数据是否和替换后的数据一致
if (cellValue !== newCellValue) {
// 不一致则代表表格内对应记录需要用 newCellValue 替换 cellValue,需要将数据加入到 finalData 数组中
finalData.push({
id: recordId,
valuesMap: { [fieldId]: newCellValue }
})
}
}

// 判断 finalData 里面是否有数据,没有数据则无需替换
if (finalData.length) {
await datasheet.updateRecordsAsync(finalData);
output.text('替换完成!')
} else {
output.text('没有找到需要替换的数据')
}