Help us understand the problem. What is going on with this article?

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

More than 5 years have passed since last update.

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したところ問題ありませんでした。

参考

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした