0

SheetJS js-xlsx ブラウザ上でのExcelファイル解析の例

SheetJS js-xlsx を使用した、ブラウザ上でのExcelファイル解析の例

SheetJS js-xlsx community version

index.html
Excelファイル選択 <input id="input_sheet" type="file">
<button type="button" onclick="inputSheet()">解析する</button>

<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.15.1/shim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.15.1/xlsx.full.min.js"></script>
main.js
var inputSheet = function () {
  var input = document.getElementById("input_sheet");
  parseSheet(input.files[0], "data", function (result) {
    // 変換後の処理
    console.log("result", result);
  });
};

// フォームで入力されたExcelのsheetNameシートをオブジェクトにする。
var parseSheet = function (file, sheetName, callback) {
  var reader = new FileReader();
  reader.onload = function (e) {
    var unit8 = new Uint8Array(e.target.result);
    var workbook = XLSX.read(unit8, {type: "array"});
    // 通常は1行目がヘッダ行となる。{header: 1} を指定で配列形式となる。
    var sheet = XLSX.utils.sheet_to_json(workbook.Sheets[sheetName], {header: 1});
    // 基本的な使い方であれば、sheet_to_jsonの結果だけでOK
    // 下記は変換を行う例
    var result = [];
    // 0行目から末尾まで走査
    for (var i = 0; i < sheet.length; i++) {
      var row = sheet[i];
      // 何か変換処理があれば行う
      console.log(i, row);
      result.push(row);
    }
    callback(result);
  };
  reader.readAsArrayBuffer(file);
};
Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away