Google apps script 通过API更改图表字体名称时出现内部服务器错误
我正在尝试使用Sheets API的请求更新图表的格式。 但是,脚本返回错误: “对sheets.spreadsheets.batchUpdate的API调用失败,错误:遇到内部错误” 下面是引发异常的代码片段:Google apps script 通过API更改图表字体名称时出现内部服务器错误,google-apps-script,google-sheets,google-sheets-api,Google Apps Script,Google Sheets,Google Sheets Api,我正在尝试使用Sheets API的请求更新图表的格式。 但是,脚本返回错误: “对sheets.spreadsheets.batchUpdate的API调用失败,错误:遇到内部错误” 下面是引发异常的代码片段: var request = [{ 'updateChartSpec': { 'chartId': chart_id, 'spec': { 'fontName': 'Arial', 'basicChart': { //to u
var request = [{
'updateChartSpec': {
'chartId': chart_id,
'spec': {
'fontName': 'Arial',
'basicChart': { //to update font name, it seems that chart type should be provided
'chartType': 'BAR'
}
}
}
}];
Sheets.Spreadsheets.batchUpdate({'requests': request}, spreadsheet_id);
有人能告诉我,请求有什么问题吗?根据Google Sheets API描述中的“示例”部分,您必须用一个全新的规范替换现有规范
如果您只想更改当前规范的一小部分,那么最简单的方法是
chartSpec
function getChartSpecs(wkbkId) {
const fields = "sheets(charts(chartId,spec),properties(sheetId,title))";
var resp = Sheets.Spreadsheets.get(wkbkId, { fields: fields });
// return an object mapped by chartId, storing the chart spec and the host sheet.
return resp.sheets.reduce(function (obj, sheet) {
if (sheet.charts) {
sheet.charts.forEach(function (chart) {
obj[chart.chartId] = {
spec: chart.spec,
sheetName: sheet.properties.title,
sheetId: sheet.properties.sheetId
};
});
}
return obj;
}, {});
}
function makeChartUpdateRequest(chartId, newSpec) {
return {
updateChartSpec: {
chartId: chartId,
spec: newSpec
}
};
}
function setNewFontOnChart(newFontName, chartId, chartSpecs) {
const wb = SpreadsheetApp.getActive();
const wbId = wb.getId();
if (!chartSpecs)
chartSpecs = getChartSpecs(wbId);
var requests = [];
if (!chartId) { // Update all charts
requests = Object.keys(chartSpecs).map(function (id) {
var chart = chartSpecs[id];
chart.spec.fontName = newFontName;
return makeChartUpdateRequest(id, chart.spec);
});
} else if (chartSpecs[chartId]) { // Update just one chart.
chartSpecs[chartId].spec.fontName = newFontName;
requests.push(makeChartUpdateRequest(chartId, chartSpecs[chartId].spec));
} else {
// oops, the given chartId is not valid.
}
if (requests.length) {
Sheets.Spreadsheets.batchUpdate({ requests: requests }, wbId);
}
}
有用链接:
字段
,以指示正在更改的属性:updateChartSpec:{chartId:“id”,spec:{fontName:“新字体”},字段:“fontName”}谢谢你,泰霍奇,谢谢你的合作!是,但对于此特定请求,不需要属性字段-。我尝试了您修改的请求,但它遇到了无效JSON负载的错误。不过,谢谢你的评论!