Webブラウザ上で Excel ファイルを作成してダウンロード - Excel Builder (.js)

Excel Builder (.js) を使って、Web ブラウザ上で動的に Excel ファイル (.xlsx) を作成し、ダウンロードする方法をご紹介します。

ソースは http://github.com/fits/try_samples/tree/master/blog/20150822/

サンプル作成

まずは、HTML を用意します。

今回は、download というリンク (a タグ) をクリックすると Excel ファイル (.xlsx) をダウンロードするようにしてみます。

Excel Builder (.js)RequireJS に依存しているため、RequireJS を読み込むようにして data-main 属性へ実行する js ファイルを指定します。

index.html
<!DOCTYPE html>
<html>
<head>
    <script data-main="app.js" src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.20/require.js"></script>
</head>
<body>

<a id="dw" href="#">download</a>

</body>
</html>

次に、Excel を生成する処理を実装します。

app.js
require(['excel-builder'], function(EB) {
    var wb = EB.createWorkbook();
    var sh = wb.createWorksheet();
    // セルへ値を設定
    sh.setData([
        ['aaa', 10],
        ['サンプル', 2],
        ['てすと', 3],
        ['計', {value: 'sum(B1:B3)', metadata: {type: 'formula'}}]
    ]);

    wb.addWorksheet(sh);

    var trg = document.getElementById("dw");

    // href 属性へ Excel ファイル内容を設定
    trg.href = 'data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,' + EB.createFile(wb);
    // ダウンロードファイル名の設定
    trg.download = 'sample.xlsx';
});

API がシンプルなので特に説明の必要は無いと思いますが、 計算式は {value: <計算式>, metadata: {type: 'formula'}} で設定できます。

また、EB.createFile(<ワークブック>) により Excel ファイルの内容を Base64 形式で取得できるので、データ形式 data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64, を先頭に付けて a タグの href 属性へ設定すれば Excel ファイルをダウンロードできるようになります。

excel-builder.js の配置

最後に、http://excelbuilderjs.com/ の Download からアーカイブファイルをダウンロード、適当なディレクトリへ解凍し、dist ディレクトリ内のファイルのどれか (例えば dist/excel-builder.compiled.min.js) を excel-builder.js という名称で app.js と同じディレクトリへ配置すれば完成です。

ファイル構成
  • index.html
  • app.js
  • excel-builder.js

動作確認

作成した index.htmlChromeFirefox で直接開いて、download リンクをクリックすると sample.xlsx をダウンロードできます。

f:id:fits:20150822020436p:plain

ダウンロードした sample.xlsx を開くと、セルの内容と計算式が正しく機能している事を確認できました。

f:id:fits:20150822020449p:plain