Web上のExcelファイルからデータを読み取る(Node.js)
備忘録。
const request = require('request'); const Excel = require('exceljs'); const getBuffer = (url) => { return new Promise((resolve, reject) => { request(url, {encoding: null}, (error, response, body) => { if (error !== null) { reject(null); } const buffer = new Buffer.from(body); resolve(buffer); }); }); } const buffer = await getBuffer('https://...'); if (buffer === null) { console.log('Couldn\'t get the file'); return; } const excel = new Excel.Workbook(); await excel.xlsx.load(buffer); const sheet = excel.worksheets[0]; const row = sheet.getRow(1); const cellValue = row.getCell('C').value; //...
exceljsというnpmを使った。ライセンスはMIT。
HTTP(S)リクエストのところで、{encoding: null}
を入れておかないとExcelファイルとして読み込めずにエラーになる。
excel.xlsx.load()
のところでawaitしてるので、asyncな関数内で使ってください。