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

如何用Google Apps Script将Google Sheet表格导入Google Doc并保留字体样式与文本颜色

解决Google Apps Script导入Sheet表格到Doc丢失字体样式和文本颜色的问题

你的代码目前仅同步了背景色、字号和粗体属性,缺少字体家族与文本颜色的设置,同时注释掉的文本颜色行还存在变量名错误,这是导致格式丢失的核心原因。

修正后的代码

function appendTable() {
  
  // Replace these values with your Sheet ID, Document ID, and Sheet Name
  
  let ssId = '<Spreadsheet Id>' // REPLACE
  let docId = '<Google doc Id>' // REPLACE
  let sheetName = '<Sheet Name>' // REPLACE
  
  // Sheet
  let range = SpreadsheetApp.openById(ssId).getSheetByName(sheetName).getDataRange()
  let values = range.getValues();
  let backgroundColors = range.getBackgrounds();
  let styles = range.getTextStyles();
  
  
 // Document
  let body = DocumentApp.openById(docId).getBody();
  let table = body.appendTable(values);
 
  for (let i=0; i<table.getNumRows(); i++) {
    for (let j=0; j<table.getRow(i).getNumCells(); j++) {
      
      let docStyles = {};
      
      docStyles[DocumentApp.Attribute.BACKGROUND_COLOR] = backgroundColors[i][j];
      docStyles[DocumentApp.Attribute.FONT_SIZE] = styles[i][j].getFontSize();
      docStyles[DocumentApp.Attribute.BOLD] = styles[i][j].isBold();
      // 同步Sheet中的字体家族
      docStyles[DocumentApp.Attribute.FONT_FAMILY] = styles[i][j].getFontFamily();
      // 同步文本颜色,修正原代码的变量错误
      docStyles[DocumentApp.Attribute.FOREGROUND_COLOR] = styles[i][j].getForegroundColor();
      
      table.getRow(i).getCell(j).setAttributes(docStyles);
    }
  }
} 

关键修正点说明

  1. 添加字体家族同步:通过styles[i][j].getFontFamily()获取Sheet单元格的字体类型,用DocumentApp.Attribute.FONT_FAMILY属性同步到Doc表格中。
  2. 修复文本颜色设置:原代码注释行的colors[i][j]是未定义变量,改为styles[i][j].getForegroundColor()正确获取Sheet单元格的文本颜色,再通过FOREGROUND_COLOR属性同步。

补充提示

如果你的Sheet表格中存在单元格内部分文本样式不一致(比如同一单元格内部分文字变色、加粗),当前代码仅能同步整单元格的统一样式。若需支持部分文本样式同步,需要进一步遍历单元格内的文本片段单独设置样式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 11:46:08