我试图导入表从谷歌工作表到谷歌文档使用谷歌应用程序脚本。到目前为止,我已经能够以部分格式将数据表导入文档。issue
是字体样式,当表被导入到google时,文本颜色不会被保留。
以下是代码:
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文档中表格的字体样式和文本颜色与工作表不一样?这是
到样品单上。谢谢
发布于 2022-09-22 04:31:43
试试这个:
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:
医生:
https://stackoverflow.com/questions/73809126
复制相似问题