Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
Help us understand the problem. What is going on with this article?

ブラウザからjsの配列をcsvとしてダウンロードする。

More than 5 years have passed since last update.

準備

以下を開発者ツールなどのコンソールで実行。

var downloadCsv = (function() {

    var tableToCsvString = function(table) {
        var str = '\uFEFF';
        for (var i = 0, imax = table.length - 1; i <= imax; ++i) {
            var row = table[i];
            for (var j = 0, jmax = row.length - 1; j <= jmax; ++j) {
                str += '"' + row[j].replace('"', '""') + '"';
                if (j !== jmax) {
                    str += ',';
                }
            }
            str += '\n';
        }
        return str;
    };

    var createDataUriFromString = function(str) {
        return 'data:text/csv,' + encodeURIComponent(str);
    }

    var downloadDataUri = function(uri, filename) {
        var link = document.createElement('a');
        link.download = filename;
        link.href = uri;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    };

    return function(table, filename) {
        if (!filename) {
            filename = 'output.csv';
        }
        var uri = createDataUriFromString(tableToCsvString(table));
        downloadDataUri(uri, filename);
    };

})();

使い方

var table = [['', ''], ['a', 'i']];
downloadCsv(table);

結果

"あ","い"
"a","i"

注意点

  • 文字列をbase64でエンコードするbtoaがマルチバイト対応していないため、日本語の文字列は非対応です。(mpywさんに修正していだきました)
  • 2次元配列以外は考慮していません。
  • IE非対応
water-cell
地球人口100億の時代への農業革命をWebテクノロジで支える
https://water-cell.jp
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