如何用Apps Script为单元格内问答内容分别设置不同格式
Google Apps Script: 为单元格内特定行设置字体颜色
以下是实现你需求的示例代码,会将单元格内以┗开头的行设为蓝色,以-开头的行保持黑色:
function formatQAInCells() { const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet(); // 可修改为目标范围,例如"A1:A100",或用getActiveRange()处理选中区域 const range = sheet.getRange("A1:A" + sheet.getLastRow()); const values = range.getValues(); const richTextValues = []; values.forEach(row => { const cellText = row[0]; if (!cellText) { richTextValues.push([SpreadsheetApp.newRichTextValue().setText("").build()]); return; } const lines = cellText.split("\n"); const richTextBuilder = SpreadsheetApp.newRichTextValue(); let currentPos = 0; lines.forEach(line => { const lineLength = line.length; let textStyle = SpreadsheetApp.newTextStyle() .setForegroundColor("#000000") // 默认黑色 .build(); if (line.startsWith("┗")) { textStyle = SpreadsheetApp.newTextStyle() .setForegroundColor("#1a73e8") // Google Sheets标准蓝色 .build(); } richTextBuilder.setTextStyle(currentPos, currentPos + lineLength, textStyle); currentPos += lineLength + 1; // 加上换行符的长度 }); richTextValues.push([richTextBuilder.setText(cellText).build()]); }); range.setRichTextValues(richTextValues); }
代码说明
- 范围选择:默认处理A列所有非空行,你可以修改
range变量指定具体范围,或者替换为sheet.getActiveRange()来处理当前选中的单元格。 - 文本拆分:用
split("\n")将单元格内容按换行符拆分为单独的行。 - 富文本构建:使用
RichTextValueBuilder逐个为每行设置字体颜色:- 以
┗开头的行应用蓝色(#1a73e8) - 以
-开头或其他行保持黑色(#000000)
- 以
- 写入结果:将构建好的富文本值批量写回目标单元格,保证格式生效。
使用步骤
- 打开你的Google表格,点击「扩展程序」→「Apps Script」
- 新建空白脚本,粘贴上述代码
- 调整
range为你需要处理的区域 - 保存脚本并运行,首次运行需完成授权验证
内容的提问来源于stack exchange,提问作者J. SungHoon
相关产品推荐
相关产品推荐

