LoginSignup
1
4

More than 3 years have passed since last update.

Tabulatorで文字コードを指定してCSVダウンロード機能を実装する

Posted at

前提条件

http://tabulator.info/  ⇒ V4.5
https://github.com/polygonplanet/encoding.js

参考

https://gist.github.com/somy-jp/593f603c386b49840b52
https://github.com/polygonplanet/encoding.js
https://qiita.com/weal/items/3b3ddfb8157047119554

内容

Tabulatorにはダウンロード機能が存在するが
公式には文字コードを指定する方法が見当たらなかったので
備忘録として。

CSVダウンロード機能

http://tabulator.info/docs/4.5/download#csv
ダウンロード機能はとても簡単。
ボタン押下時のイベントに以下のコードを書けば終わり。

table.download("csv", "data.csv");

実際に問題を再現

試しに実装しました。
image.png

ダウンロードすると...
6行目にしっかり文字化けが...
image.png

解決策

ライブラリの中身を見ていくとdownloadReadyでblobにする処理を自前で書けるみたい。
以下のコードを検索かけると見つかる。

tabulator.js
blob = this.table.options.downloadReady.call(this.table, data, blob);

ライブラリを追加するのとTabulatorのインスタンス作成時に
downloadReadyの処理を追記

  <script src="./js/encoding.js"></script>
    var table = new Tabulator("#example-table", {
      height: 205, // set height of table (in CSS or here), this enables the Virtual DOM and improves render speed dramatically (can be any valid css height value)
      data: table_data, //assign data to table
      layout: "fitColumns", //fit columns to width of table (optional)
      columns: [ //Define Table Columns
        { title: "Name", field: "name", width: 150 },
        { title: "Age", field: "age", align: "left", formatter: "progress" },
        { title: "Favourite Color", field: "col" },
        { title: "Date Of Birth", field: "dob", sorter: "date", align: "center" },
      ],
      // ここを新規に追記
      downloadReady: function (data, blob) {
        var str_array = Encoding.stringToCode(data);
        var sjis_array = Encoding.convert(str_array, "SJIS", "UNICODE");
        var uint8_array = new Uint8Array(sjis_array);
        var newBlob = new Blob([uint8_array], { type: 'text/csv' });
        return newBlob;
      }
    });

これで解決
image.png

1
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
1
4