Azure FunctionsでAzure Storageに置いたExcelファイルを取ってきて、編集する

やりたいこと

シフト表を作りたい。

  • シフト表のテンプレートはAzure Storageに置いている。
  • スケジュールの調整は、スケジュール調整サービス(調整さんとか、TONTONとか)でやっている。

スケジュール調整サービスから結果を取り出し、シフト表のテンプレートに反映して、ダウンロードしたい。

やったこと

とりあえず、Azure Functionsで、ExcelファイルをAzure Storageから取ってきて、ダウンロードできるところまでを作ってみる。
ExcelJavaScriptで操作するライブラリは exceljs を使ってみた。

github.com

コード

特に変わったことはしていない。
ハマったところは、function.json"dataType": "binary" を設定するところ。設定しないと workbook.xlsx.load でコケてしまう。

index.js

const Excel = require('exceljs');

module.exports = async function (context, req) {
    context.log('JavaScript HTTP trigger function processed a request.');

    var workbook = new Excel.Workbook();
    await workbook.xlsx.load(context.bindings.shiftScheduleTemplate);

    context.res.setHeader("Content-Type", "application/vnd.ms-excel")
    context.res.setHeader("Content-Disposition", "attachment; filename=ShiftSchedule.xlsx");
    var buff = await workbook.xlsx.writeBuffer();
    context.res.body = buff;
};

function.json

{
  "bindings": [
    {
      "type": "blob",
      "name": "shiftScheduleTemplate",
      "direction": "in",
      "dataType": "binary",
      "path": "assets/shiftschedule-template.xlsx",
      "connection": "Assets_STORAGE"
    }
  ]
}