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

2024年5月25日土曜日

Google Slidesで現在選択している表に値を入れたい3 - Insert values into the active table3


上記のリンク先では、値の数に応じて行を追加しました。
In the linked article above, rows were added to the table depending on the number of values.


今回は、逆に行を削除するコードを試してみます。
This time, I will try the code that deletes rows according to the number of values.



今回の例でも、3行3列の表を配置しておきます。
In this example, a 3x3 table will be pre-placed on the slide.


表に入れる値は、2行3列の配列を用意します。
Prepare a 2x3 array of values to insert into the table.
const values = [
['Value 1', 'Value 2', 'Value 3'],
['Value 4', 'Value 5', 'Value 6']
];



Code.gs
function insertValuesIntoSelectedTable() {
const presentation = SlidesApp.getActivePresentation();
const selection = presentation.getSelection();
const pageElement = selection.getPageElementRange().getPageElements()[0];
const table = pageElement.asTable();
const values = [
['Value 1', 'Value 2', 'Value 3'],
['Value 4', 'Value 5', 'Value 6']
];

removeDescriptionsRow(table, values);

for (var row = 0; row < values.length; row++) {
for (var col = 0; col < values[row].length; col++) {
if (row < table.getNumRows() && col < table.getNumColumns()) {
table.getCell(row, col).getText().setText(values[row][col]);
}
}
}
}

function removeDescriptionsRow(table, values) {
const tableRows = table.getNumRows();
const valuesLength = values.length;

// 行を削除する数を計算
const rowsToRemove = tableRows - valuesLength;

if (rowsToRemove > 0) {
for (let i = 0; i < rowsToRemove; i++) {
const rowIndex = table.getNumRows() - 1; // 常に最後の行のインデックスを取得
if (rowIndex >= 0) {
table.getRow(rowIndex).remove();
} else {
Logger.log("テーブルの行が存在しません。");
break;
}
}
}
}


表を選択して、insertValuesIntoSelectedTable() を実行します。
Select the table and execute the insertValuesIntoSelectedTable() function.


下段の一行が削除されて、用意した配列の値がすべて入力されます。
The bottom row is deleted and all values from the prepared array are inserted.


Reference

Class Table > remove()

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 に課題が上がっていることが...