15
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Google Apps ScriptでShift_JIS変換したcsvをメール添付送信

Posted at

Google Apps Script で2次元配列のデータを csv に変換してメールで送る方法を調べてみました。

前提

  • 2次元配列データをcsvに変換する
  • Shift_JIS にエンコードし添付ファイルでメール送信

コード

csv.gs
function sendMail() {
  var data = [
    ["あああ","いいい","ううう"],
    ["aaa","bbb","ccc"]
    ];
  var csvFile = convertValuesToCsvFile_(data)
  var blob = Utilities.newBlob("", 'text/comma-separated-values', 'mycsv.csv');
  blob.setDataFromString(csvFile, "Shift_JIS");

  var mailTo = "your@email.here";
  var subject = "CSV file";
  var body = "CSV file";
  var options = {attachments: [blob]};
  MailApp.sendEmail(mailTo, subject, body, options);
}

function convertValuesToCsvFile_(data) {
  try {
    var csvFile = undefined;

    // Loop through the data in the range and build a string with the CSV data
    if (data.length > 1) {
      var csv = "";
      for (var row = 0; row < data.length; row++) {
        for (var col = 0; col < data[row].length; col++) {
          if (data[row][col].toString().indexOf(",") != -1) {
            data[row][col] = "\"" + data[row][col] + "\"";
          }
        }

        // Join each row's columns
        // Add a carriage return to end of each row, except for the last one
        if (row < data.length-1) {
          csv += data[row].join(",") + "\r\n";
        }
        else {
          csv += data[row];
        }
      }
      csvFile = csv;
    }
    return csvFile;
  }
  catch(err) {
    Logger.log(err);
    Browser.msgBox(err);
  }
}

補足

Blob#setDataFromString(str, charset)を使うと文字列を文字コード指定でセットできるので、まず Utilities.newBlob("", 'text/comma-separated-values', 'mycsv.csv'); で空の Blob を作ってます。

このコードでgmailからdownloadしたところ問題ありませんでした。

参考

15
13
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
15
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?