GASでスプレッドシートをカスタマイズしたいけど、テキストのスタイルを細かく制御する方法がわからん?
今回は、getTextStyles()
メソッドを使って、セル内のフォントや色、太字・斜体などを取得・管理する方法を詳しく解説するばい!
1. getTextStyles()メソッドとは?
GASでは、getTextStyles()
を使うと、セル内のテキストスタイルを取得できるっちゃね。
const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
const range = sheet.getRange("A1:C3");
const styles = range.getTextStyles();
styles.forEach((row, rowIndex) => {
row.forEach((style, colIndex) => {
console.log(`セル ${String.fromCharCode(65 + colIndex)}${rowIndex + 1} のスタイル`);
console.log(`フォント: ${style.getFontFamily()}`);
console.log(`サイズ: ${style.getFontSize()}pt`);
console.log(`太字: ${style.isBold()}`);
});
});
このコードを実行すると、A1からC3の各セルに適用されているテキストスタイルがログに表示されるばい。
2. getTextStyles()で取得できる情報
getTextStyles()
メソッドは、以下の情報を取得できるっちゃね。
- フォントファミリー (
getFontFamily()
) - フォントサイズ (
getFontSize()
) - 文字色 (
getForegroundColor()
) - 太字 (
isBold()
) - 斜体 (
isItalic()
) - 下線 (
isUnderline()
) - 取り消し線 (
isStrikethrough()
)
3. 応用例:スタイルが統一されているかチェック!
スプレッドシートで、指定範囲のセルスタイルが統一されているか確認するスクリプトを紹介するばい。
function checkTextStyles() {
const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
const range = sheet.getDataRange();
const styles = range.getTextStyles();
const baseStyle = styles[0][0];
let differences = [];
styles.forEach((row, i) => {
row.forEach((style, j) => {
if (style.getFontFamily() !== baseStyle.getFontFamily() ||
style.getFontSize() !== baseStyle.getFontSize() ||
style.isBold() !== baseStyle.isBold()) {
differences.push(`${String.fromCharCode(65 + j)}${i + 1}`);
}
});
});
if (differences.length > 0) {
console.log(`異なるスタイルのセル: ${differences.join(", ")}`);
} else {
console.log("全セルのスタイルが統一されとるばい!");
}
}
これを実行すると、フォント・サイズ・太字の違いをチェックして、異なるセルを特定できるばい。
4. スタイルを一括適用する方法
取得したスタイルを別のセルに適用したいときは、こんな感じでやるっちゃ!
function applyTextStyle() {
const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
const sourceRange = sheet.getRange("A1");
const targetRange = sheet.getRange("B1:D1");
const sourceStyle = sourceRange.getTextStyle();
const newStyle = SpreadsheetApp.newTextStyle()
.setFontFamily(sourceStyle.getFontFamily())
.setFontSize(sourceStyle.getFontSize())
.setBold(sourceStyle.isBold())
.build();
targetRange.setTextStyle(newStyle);
}
A1のスタイルをB1~D1に適用するスクリプトじゃ。
5. まとめ
getTextStyles()
を使うと、スプレッドシート内のテキストスタイルを細かく制御できるばい。
✅ スタイルを取得してログに出力できる! ✅ ルール違反のセルを検出できる! ✅ スタイルを他のセルに適用できる!
スプレッドシートの見た目を統一したいときに、ぜひ活用してみんしゃい!
コメント