2

I trying create button in page and with (kind OpenFileDialog ) select file excel. Parse this file. Find my question, but dont work. Reading excel file into array using javascript

$("#fileInput").on("change", function(e) {
  var file = e.target.files[0];
  // input canceled, return
  if (!file) return;
  var FR = new FileReader();
  FR.onload = function(e) {
    var data = new Uint8Array(e.target.result);
    var workbook = XLSX.read(data, {
      type: 'array'
    });
    var firstSheet = workbook.Sheets[workbook.SheetNames[0]];
    // header: 1 instructs xlsx to create an 'array of arrays'
    var result = XLSX.utils.sheet_to_json(firstSheet, {
      header: 1
    });
    // data preview
    var output = document.getElementById('result');
    output.innerHTML = JSON.stringify(result, null, 2);
  };
  FR.readAsArrayBuffer(file);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.14.5/xlsx.full.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type="file" id="fileInput" value="Choose Files!" accept=".xls, .xlsx" />
<!--расширение файла -->
<pre id="result"></pre>

1 Answer 1

1

You can use an arrayBuffer, the File object inherits the arrayBuffer() method from Blob, the following works (you just need to adapt it to jQuery a bit):

<input type="file" id="fileInput" value="Choose Files!" accept=".xls, .xlsx" />

<pre id="result"></pre>

<script lang="javascript" src="https://cdn.sheetjs.com/xlsx-0.18.12/package/dist/xlsx.full.min.js"></script>
const $ = selector => document.querySelector(selector)

const input = $('#fileInput')

input.addEventListener('change', async (e) => {
  const file = e.target.files[0]

  if (!file) return

  const data = await file.arrayBuffer()

  const wb = XLSX.read(data)
  const ws = wb.Sheets[wb.SheetNames[0]]
  const result = XLSX.utils.sheet_to_json(ws, {
    header: 1
  })

  $('#result').innerHTML = JSON.stringify(result, null, 2)
})

Preview:
preview

Demo in codi.link

Sign up to request clarification or add additional context in comments.

1 Comment

TY very much! If you don't mind, you can comment on the lines

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.