LoginSignup
4

More than 5 years have passed since last update.

Node.jsでエクセルファイルを読み込む

Last updated at Posted at 2017-12-24

Node.jsでエクセルを扱いたい。「ya-csv」でcsvを読み書きするみたいにエクセルを読み書きしたい。

使うのは exceljs

一通り書いてみたのが以下のコード

const fs = require('fs');
const excel = require('exceljs');

exports.readXlsxData =(filePath, columnsFromHeader)=>{
  const dataArr =[];
  const workbook = new excel.Workbook();
  workbook.xlsx.readFile(filePath).then(()=>{
    //最初のsheetを読み込んでいる
    const sheet = workbook.getWorksheet(1);
    let columIndex=1;
    let rowIndex=1;
    if(columnsFromHeader){
         //ヘッダー行ありの場合、1行目がヘッダーで各項目がキーになる
         //連想配列を返す
      const headerRow =[];
      while(sheet.getCell(1, columIndex).value !== null){
        headerRow.push(sheet.getCell(1, columIndex++).value);
      }
      columIndex--;
      rowIndex++;
      while(sheet.getCell(rowIndex, 1).value !== null){
        const data ={};
        let col=1;
        while(col<=columIndex){
          data[headerRow[col-1]] =sheet.getCell(rowIndex, col++).value;
        }
        dataArr.push(data);
        rowIndex++;
      }
    }else{
            //ヘッダー行なしの場合
            //配列の配列を返す
      while(sheet.getCell(rowIndex, 1).value !== null){
        const data =[];
        while(sheet.getCell(rowIndex, columIndex).value !== null){
          data.push(sheet.getCell(rowIndex, columIndex++).value);
        }
        dataArr.push(data);
        columIndex=1;
        rowIndex++;
      }
    }
    return(dataArr);
  });
};

columnsFromHeaderのオプションだけつけている状態
スクリーンショット 2017-12-24 22.48.29.png

readXlsxData(filePath) だと列ヘッダーなし
→配列の配列で返ってくる。1行ごとに順に配列になっている

readXlsxData(filePath, true) だと列ヘッダーあり
→連想配列で返ってくる。先頭行の項目はキーになる

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
4