Home > Software engineering >  Read excel file in react native
Read excel file in react native

Time:03-22

I try to use the data of an existing excel file in a react native application. I tried with xlsx and Exceljs but each time I had mistakes. What is the best way to use Excel data (This means retrieving data from each cell in the excel table) in a reactnative application please ?

This is an example of a code that I tried to use, but it's wrong (I have the following mistake: Unhandled promise rejection, [TypeError: undefined is not an object (evaluating 'i.constants.F_OK')] )

var Excel = require('exceljs');
var workbook = new Excel.Workbook();
workbook.xlsx.readFile("Liste_qcm2.xlsx")
    .then(function() {
        ws = workbook.getWorksheet("Sheet1")
        cell = ws.getCell('A1').value
        console.log(cell)
    });

thank you in advance

CodePudding user response:

I haven't used excels, but it appears that readFile is for NodeJS (it takes a file path, not a File object).

Here's a snippet for SheetJS (xlsx) that runs client-side:

    const fileData = await file.arrayBuffer()
    const workbook = XLSX.read(fileData)
    const firstSheet = workbook.SheetNames[0]
    const worksheet = workbook.Sheets[firstSheet]

The file value is a File object from a file Input.

UPDATE The above snippet gets the File object from <Input type="file" ...> element. ReactNative doesn't built-in support for reading/writing files natively, but there are modules that bridge the gap, e.g. ReactNative

Here is the SheetJS ReactNative demo that shows how to get up and running.

Here's a snippet that reads each column in the 1st row of data. You can turn this into a double loop to visit every cell in the spreadsheet.

  function getHeaderRow(sheet: XLSX.WorkSheet) {
    const headers = []
    const range = XLSX.utils.decode_range(sheet['!ref'] ?? '')
    const row = range.s.r
    for (let col = range.s.c; col <= range.e.c;   col) {
      const cell = sheet[XLSX.utils.encode_cell({ c: col, r: row })] /* find the cell in the first row */
      const header = (cell && cell.t) ? XLSX.utils.format_cell(cell) : "UNKNOWN "   col
      headers.push(header)
    }
    return headers
  }
  • Related