Apps Script公式リファレンス: Apps Script Reference |障害・課題追跡: IssueTracker |Google Workspace: Status Dashboard - Summary

2024年5月13日月曜日

Google Slidesの表でセルの書式を設定したい - Format cells in a table


Googleスライドに配置した表で、セルの書式を設定するコードを試しました。
I tried to apply formatting to the cells in a table in Google Slides using Apps Script.
  • セルの文字色:  Font color
  • 太字:  Bold
  • 文字サイズ: Font size
  • 背景色: Background color
  • 垂直中央: Vertical alignment
  • 水平中央:  Horizontal alignment



今回使うスライドの例
An example of the slide used for this demonstration.



Code.gs
function formatCells() {
var presentation = SlidesApp.getActivePresentation();
var slide = presentation.getSelection().getCurrentPage();
var tables = slide.getTables();

var table = tables[0];
var numRows = table.getNumRows();
var numCols = table.getNumColumns();

for (var i = 0; i < numRows; i++) {
for (var j = 0; j < numCols; j++) {
var cell = table.getCell(i, j);
var textStyle = cell.getText().getTextStyle();
textStyle.setForegroundColor('#ffffff');// fontColor
textStyle.setBold(true);// bold
textStyle.setFontSize(14);// fontSize

cell.getFill().setSolidFill('#0000cd');// backgroundColor
cell.setContentAlignment(SlidesApp.ContentAlignment.MIDDLE);// verticalAlign
cell.getText().getParagraphStyle().setParagraphAlignment(SlidesApp.ParagraphAlignment.CENTER);// horizontalAlign
}
}
}


formatCells()を実行すると、コードで設定したように表の見た目を変更できました。
Running formatCells() successfully changed the appearance of the table as specified in the code.


Tips

ChatGPT4とGeminiに質問した回答を参考にしましたが、セル内の水平方向の中央揃えは一発で書いてくれず、何度も調整が必要でした。
It took multiple attempts to achieve successful horizontal centering of text within cells, as neither ChatGPT-4 nor Gemini provided a working solution in one go.

cell.getText().getParagraphStyle().setParagraphAlignment(SlidesApp.ParagraphAlignment.CENTER);// horizontalAlign


ContentAlignmentは垂直方向のみ設定できるらしい
It seems that ContentAlignment can only be used for vertical alignment.

cell.setContentAlignment(SlidesApp.ContentAlignment.MIDDLE);// verticalAlign



Format cells in a table within Google Slides using Apps Script.

Reference

Google Slidesの表をApps Scriptで取得したい - Get tables in Slides


Class Table > getCell(rowIndex, columnIndex)

Class TableCell > getText()

Class TableCell > getFill()

Class TableCell > setContentAlignment(contentAlignment)

Class TextRange > getTextStyle()

Class TextRange > getParagraphStyle()

Class ParagraphStyle > setParagraphAlignment(alignment)

Class TextStyle > setForegroundColor

Class TextStyle > setBold(bold)

Class TextStyle > setFontSize(fontSize)

Latest post

Google Apps Scriptの障害時はIssueTrackerを見てみる - Incidents for Apps Script are reported on Issue Tracker

IssueTracker > Apps Script issues https://issuetracker.google.com/savedsearches/566234 Google Apps Scriptの障害時は IssueTracker に課題が上がっていることが...