You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Apps Script跨表格取值并保留单元格红色字体格式?

Apps Script跨表格保留单元格字体格式方案

getValue()和getDisplayValue()仅能获取单元格文本内容,无法携带格式信息,所以靠这两个方法没法直接保留红色字体格式。不用单独写第二个函数,直接在原有逻辑里整合格式处理即可,分两种场景实现:

场景1:整单元格复制内容+格式

用copyTo()方法直接把源单元格的内容和格式批量复制到目标位置,适合需要完整保留单元格所有格式的情况:

// 先获取源文件和目标文件的Sheet对象(示例)
const sourceFile = SpreadsheetApp.openById("源文件ID");
const sourceSheet = sourceFile.getSheetByName("源工作表");
const targetFile = SpreadsheetApp.openById("目标文件ID");
const targetSheet = targetFile.getSheetByName("目标工作表");

// 指定源单元格和目标单元格
const sourceRange = sourceSheet.getRange("A1");
const targetRange = targetSheet.getRange("B1");

// 只复制格式(如果已经用getValue获取了内容,单独补格式)
sourceRange.copyTo(targetRange, SpreadsheetApp.CopyPasteType.PASTE_FORMAT, false);

// 或者同时复制内容和格式
// sourceRange.copyTo(targetRange, SpreadsheetApp.CopyPasteType.PASTE_ALL, false);

场景2:精准控制格式(比如仅提取红色文字片段)

如果源单元格只有部分文字是红色,或者需要自定义格式应用逻辑,用RichTextValue解析源单元格的格式信息,再构建带格式的文本写入目标单元格:

// 延续上述获取Sheet和Range的逻辑
const sourceRichText = sourceRange.getRichTextValue();

// 如果整单元格都是红色字体,直接构建并写入
const targetRichText = SpreadsheetApp.newRichTextValue()
  .setText(sourceRichText.getText())
  .applyTextStyle(0, sourceRichText.getText().length, sourceRichText.getTextStyle())
  .build();
targetRange.setRichTextValue(targetRichText);

// 如果仅部分文字是红色,遍历格式片段逐个处理
const sourceRuns = sourceRichText.getRuns();
const targetBuilder = SpreadsheetApp.newRichTextValue().setText(sourceRichText.getText());
sourceRuns.forEach(run => {
  const start = run.getStartIndex();
  const end = run.getEndIndex();
  targetBuilder.applyTextStyle(start, end, run.getTextStyle());
});
targetRange.setRichTextValue(targetBuilder.build());

内容的提问来源于stack exchange,提问作者TinaT

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 14:25:04