首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何以相同的文本颜色和格式将谷歌工作表复制到Google?

如何以相同的文本颜色和格式将谷歌工作表复制到Google?
EN

Stack Overflow用户
提问于 2022-09-22 03:43:05
回答 2查看 85关注 0票数 1

我试图导入表从谷歌工作表到谷歌文档使用谷歌应用程序脚本。到目前为止,我已经能够以部分格式将数据表导入文档。issue是字体样式,当表被导入到google时,文本颜色不会被保留。

以下是代码:

代码语言:javascript
运行
复制
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();
     // docStyles[DocumentApp.Attribute.FOREGROUND_COLOR] = colors[i][j];
      
      table.getRow(i).getCell(j).setAttributes(docStyles);
    }
  }
} 

当脚本运行时,它从工作表中导入下表:

但是,Google中的导入表失去了格式,如下所示:

请您指导我在这里缺少什么,为什么Google文档中表格的字体样式和文本颜色与工作表不一样?这是

链接

到样品单上。谢谢

EN

Stack Overflow用户

发布于 2022-09-22 04:31:43

试试这个:

代码语言:javascript
运行
复制
function appendTable() {
  const ss = SpreadsheetApp.openById("ssid")
  const sh = ss.getSheetByName("Sheet0");
  const rg = sh.getRange(1, 1, sh.getLastRow(), sh.getLastColumn())
  const vs = rg.getValues();
  const bs = rg.getBackgrounds();
  const fws = rg.getFontWeights();
  const fss = rg.getFontSizes();
  const sts = rg.getTextStyles();
  const d = DocumentApp.getActiveDocument();
  const b = d.getBody();
  const tbl = b.appendTable(vs);
  vs.forEach((r,i) => {
    r.forEach((c,j) => {
      let sty = {};
      sty[DocumentApp.Attribute.BACKGROUND_COLOR] = bs[i][j];
      sty[DocumentApp.Attribute.FONT_SIZE] = fss[i][j];
      sty[DocumentApp.Attribute.BOLD] = (fws[i][j] == 'bold') ? true: false;
      sty[DocumentApp.Attribute.FOREGROUND_COLOR] = sts[i][j].getForegroundColorObject().asRgbColor().asHexString();
      tbl.getRow(i).getCell(j).setAttributes(sty);
    });
  });
}

Sheet0:

医生:

票数 1
EN
查看全部 2 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73809126

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档