22
27

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Posted at

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);
};
22
27
0

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
22
27

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?