LoginSignup
5
4

More than 3 years have passed since last update.

GASでGmailにテーブルを作成するコード

Posted at

最近、Gmailにテーブルを作れると知ったのでコード作成。
このテーブルの色合いが良いとは思っていないが、再度HTML,CSS作るのも嫌だったのでメモ代わりに記事作成。

第二引数にtypeを入れることによって項目有り無しの変更を加えてある。

▼項目なし
2020-06-09_17h35_46.png

▼項目あり
2020-06-09_17h35_13.png

下記コードです。

createMaildraft.gs

function createMaildraft() {

  const shtName = 'table';
  const sht = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(shtName);
  const values = sht.getRange('A2:C5').getValues();

  // 本文(html)以外の設定  
  const recipient = '';
  const subject = '件名';
  const body = ''; 

    // 本文の設定
  let html = `
  本文作成

  ▼テーブルの挿入
  ${makeTable_(values, 1)}

  挿入完了
  `;

  // 空白は<br>に変換しないと改行にならないので処理
  html = html.replace(/\n/g, '<br>');
  GmailApp.createDraft(recipient, subject, body, {htmlBody :html})
}

makeTable_.gs
/**
* 二次元配列からtableのHTMLを返すコード
* type:0 項目名なし(デフォルト)
* type:1 項目名あり
* 
* @param {object}  二次元配列のデータ
* @param {number}  テーブル作成の形
* @return {string} tableのHTMLコード
*/

function makeTable_(values, type = 0) {

  let table = "<table style = 'width: auto; border-spacing: 0;font-size:14px; border: 1px solid #ddd;'>";

  for(let i=0; i<values.length; i++){
    table += '<tr>';

    if (i === 0 && type === 1) {
      for(let cell of values[i]){
        table += `<th style = 'padding: 8px 15px; border: 1px solid #fff; background: #888; font-weight: bold; color:white;'>${cell}</th>`;
      }
    } else if (i % 2 === 1) {
      for(let cell of values[i]){
        table += `<td style = 'padding: 8px 15px; border: 1px solid #ddd;'>${cell}</td>`;
      }
    } else {
      for(let cell of values[i]){
        table += `<td style = 'padding: 8px 15px; border: 1px solid #ddd; background: #f5f5f5;'>${cell}</td>`;
      }
    }
    table += '</tr>';
  }
  table += '</table>';

  return table;
}
5
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
4