Javascript excel to json

NOTE: Not 100% Cross Browser

Check browser compatibility @ http://caniuse.com/#search=FileReader

as you will see people have had issues with the not so common browsers, But this could come down to the version of the browser.. I always recommend using something like caniuse to see what generation of browser is supported… This is only a working answer for the user, not a final copy and paste code for people to just use..

The Fiddle: http://jsfiddle.net/d2atnbrt/3/

THE HTML CODE:

<input type="file" id="my_file_input" />
<div id='my_file_output'></div>

THE JS CODE:

var oFileIn;

$(function() {
    oFileIn = document.getElementById('my_file_input');
    if(oFileIn.addEventListener) {
        oFileIn.addEventListener('change', filePicked, false);
    }
});


function filePicked(oEvent) {
    // Get The File From The Input
    var oFile = oEvent.target.files[0];
    var sFilename = oFile.name;
    // Create A File Reader HTML5
    var reader = new FileReader();

    // Ready The Event For When A File Gets Selected
    reader.onload = function(e) {
        var data = e.target.result;
        var cfb = XLS.CFB.read(data, {type: 'binary'});
        var wb = XLS.parse_xlscfb(cfb);
        // Loop Over Each Sheet
        wb.SheetNames.forEach(function(sheetName) {
            // Obtain The Current Row As CSV
            var sCSV = XLS.utils.make_csv(wb.Sheets[sheetName]);   
            var oJS = XLS.utils.sheet_to_row_object_array(wb.Sheets[sheetName]);   

            $("#my_file_output").html(sCSV);
            console.log(oJS)
        });
    };

    // Tell JS To Start Reading The File.. You could delay this if desired
    reader.readAsBinaryString(oFile);
}

This also requires https://cdnjs.cloudflare.com/ajax/libs/xls/0.7.4-a/xls.js to convert to a readable format, i’ve also used jquery only for changing the div contents and for the dom ready event.. so jquery is not needed

This is as basic as i could get it,

EDIT — Generating A Table

The Fiddle: http://jsfiddle.net/d2atnbrt/5/

This second fiddle shows an example of generating your own table, the key here is using sheet_to_json to get the data in the correct format for JS use..

One or two comments in the second fiddle might be incorrect as modified version of the first fiddle.. the CSV comment is at least

Test XLS File: http://www.whitehouse.gov/sites/default/files/omb/budget/fy2014/assets/receipts.xls

This does not cover XLSX files thought, it should be fairly easy to adjust for them using their examples.

In this article, you will see how to convert excel file data to JSON format in Javascript. There is a popular library called Apache POI to read excel file data, but this library is all about doing it server-side. In some cases, you don’t want to allow users to upload an excel file without doing the proper validation. So in order to validate an excel file, you have to read it on the client-side itself before uploading it to the server.

This article shows you how can you read an excel file to convert it into JSON on the client side only. We are going to use a Javascript library (xlsx.min.js) provided by SheetJS to convert excel file data to JSON.

Excel file data to JSON using Javascript
Excel file data to JSON using Javascript

It is very simple to do in Javascript using the xlsx.min.js library. Follow the below simple steps:

1. Define HTML

We have defined an HTML <input> tag with type=”file” to choose an excel file. And a <button> tag to upload the file and a <textarea> tag to display the resulting JSON format data.

<h1>Upload an excel file to convert into JSON</h1>
<!-- Input element to upload an excel file -->
<input type="file" id="file_upload" />
<button onclick="upload()">Upload</button>	
<br><br>
<!-- container to display the json result -->
<textarea id="json-result" style="display:none;height:500px;width:350px;"></textarea>

2. Include the library in the HTML file

Include the CDN link of library xlsx.min.js in the <head> tag of an HTML file as follows:

<head>
   <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.17.5/xlsx.min.js"></script>
</head>

3. Write the Javascript logic

Write the below javascript code to extract the data in JSON format from the uploaded excel file.

   // Method to upload a valid excel file
  function upload() {
	var files = document.getElementById('file_upload').files;
	if(files.length==0){
	  alert("Please choose any file...");
	  return;
	}
	var filename = files[0].name;
	var extension = filename.substring(filename.lastIndexOf(".")).toUpperCase();
	if (extension == '.XLS' || extension == '.XLSX') {
		excelFileToJSON(files[0]);
	}else{
		alert("Please select a valid excel file.");
	}
  }
  
  //Method to read excel file and convert it into JSON 
  function excelFileToJSON(file){
	  try {
		var reader = new FileReader();
		reader.readAsBinaryString(file);
		reader.onload = function(e) {

			var data = e.target.result;
			var workbook = XLSX.read(data, {
				type : 'binary'
			});
			var result = {};
			workbook.SheetNames.forEach(function(sheetName) {
				var roa = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]);
				if (roa.length > 0) {
					result[sheetName] = roa;
				}
			});
			//displaying the json result
			var resultEle=document.getElementById("json-result");
			resultEle.value=JSON.stringify(result, null, 4);
			resultEle.style.display='block';
			}
		}catch(e){
		    console.error(e);
		}
  }

Explanation:

  • Here we have defined a method upload() that will be called on the upload button click. This method allows the user to upload only a valid excel file.
  • The method excelFileToJSON() is defined to read the uploaded excel file and convert data into JSON format.
  • Inside excelFileToJSON(), we have read the data of the excel file by using a file reader as a binary string using readAsBinaryString() method.
  • After that, we used XLSX which has a built-in facility to convert our binary string into a JSON object. And the XLSX.utils.sheet_to_row_object_array() method is used to read each sheet of data in a loop by iterating the workbook.
  • To beautify and display the JSON result, we have used JSON.stringify(result, null, 4).

Complete code example to extract the excel data in JSON

Putting all the above code in a single HTML document as follow:

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1">  
	<title>Excel to JSON | Javacodepoint</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.17.5/xlsx.min.js"></script>    
  </head>
  <body>
  	<h1>Upload an excel file to convert into JSON</h1>
    <input type="file" id="file_upload" />
    <button onclick="upload()">Upload</button>	
    <br>
    <br>
	<!-- container to display the json result -->
    <textarea id="json-result" style="display:none;height:500px;width:350px;"></textarea>
    <script>
	
      // Method to upload a valid excel file
	  function upload() {
		var files = document.getElementById('file_upload').files;
		if(files.length==0){
		  alert("Please choose any file...");
		  return;
		}
		var filename = files[0].name;
		var extension = filename.substring(filename.lastIndexOf(".")).toUpperCase();
		if (extension == '.XLS' || extension == '.XLSX') {
			excelFileToJSON(files[0]);
		}else{
			alert("Please select a valid excel file.");
		}
	  }
	  
	  //Method to read excel file and convert it into JSON 
	  function excelFileToJSON(file){
		  try {
			var reader = new FileReader();
			reader.readAsBinaryString(file);
			reader.onload = function(e) {

				var data = e.target.result;
				var workbook = XLSX.read(data, {
					type : 'binary'
				});
				var result = {};
				workbook.SheetNames.forEach(function(sheetName) {
				var roa = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]);
				if (roa.length > 0) {
					result[sheetName] = roa;
				}
			  });
				//displaying the json result
				var resultEle=document.getElementById("json-result");
				resultEle.value=JSON.stringify(result, null, 4);
				resultEle.style.display='block';
				}
			}catch(e){
				console.error(e);
			}
	  }
    </script>
  </body>
</html>

Test and Live Demo

Let’s assume a sample Excel file(students.xlsx) that we are going to upload. As you can see in the below image this excel file contains the student’s data(name, address, email id, and age).

convert excel to json javascript

Let’s see the result once we upload the above excel file to this application.

Excel file data to convert into JSON

Conclusion

In this article, you have seen how to upload an excel file to convert it into JSON format using Javascript on the client side. As it will be very helpful when you want to validate the excel data before going to upload it to the server.

Related articles:

  • File upload validations in javascript
  • Drag & Drop or Browse – File upload Feature in JavaScript
  • Preview an image before uploading using Javascript
  • Preview an image before uploading using jQuery

tag:?
license:mit
build:?
coverage:?
codecov.io

npm:
dependencies:?
devDependency Status

Convert Excel Files to JSON

What

Parse Excel xlsx files into a list of javascript objects and optionally write that list as a JSON encoded file.

You may organize Excel data by columns or rows where the first column or row contains object key names and the remaining columns/rows contain object values.

Expected use is offline translation of Excel data to JSON files, although
all methods are exported for other uses.

Install

$ npm install excel-as-json --save-dev

Use

convertExcel = require('excel-as-json').processFile;
convertExcel(src, dst, options, callback);
  • src: path to source Excel file (xlsx only)
  • dst: path to destination JSON file. If null, simply return the parsed object tree
  • options: an object containing
    • sheet: 1 based sheet index as text — default ‘1’
    • isColOriented: are object values in columns with keys in column A — default false
    • omitEmptyFields: omit empty Excel fields from JSON output — default false
    • convertTextToNumber: if text looks like a number, convert it to a number — default true
  • callback(err, data): callback for completion notification

NOTE If options are not specified, defaults are used.

With these arguments, you can:

  • convertExcel(src, dst)
    will write a row oriented xlsx sheet 1 to dst as JSON with no notification
  • convertExcel(src, dst, {isColOriented: true})
    will write a col oriented xlsx sheet 1 to file with no notification
  • convertExcel(src, dst, {isColOriented: true}, callback)
    will write a col oriented xlsx to file and notify with errors and parsed data
  • convertExcel(src, null, null, callback)
    will parse a row oriented xslx using default options and return errors and the parsed data in the callback

Convert a row/col oriented Excel file to JSON as a development task and
log errors:

convertExcel = require('excel-as-json').processFile

options = 
    sheet:'1'
    isColOriented: false
    omitEmtpyFields: false

convertExcel 'row.xlsx', 'row.json', options, (err, data) ->
	if err then console.log "JSON conversion failure: #{err}"

options = 
    sheet:'1'
    isColOriented: true
    omitEmtpyFields: false

convertExcel 'col.xlsx', 'col.json', options, (err, data) ->
	if err then console.log "JSON conversion failure: #{err}"

Convert Excel file to an object tree and use that tree. Note that
properly formatted data will convert to the same object tree whether
row or column oriented.

convertExcel = require('excel-as-json').processFile

convertExcel 'row.xlsx', undefined, undefined, (err, data) ->
	if err throw err
	doSomethingInteresting data
	
convertExcel 'col.xlsx', undefined, {isColOriented: true}, (err, data) ->
	if err throw err
	doSomethingInteresting data

Why?

  • Your application serves static data obtained as Excel reports from
    another application
  • Whoever manages your static data finds Excel more pleasant than editing JSON
  • Your data is the result of calculations or formatting that is
    more simply done in Excel

What’s the challenge?

Excel stores tabular data. Converting that to JSON using only
a couple of assumptions is straight-forward. Most interesting
JSON contains nested lists and objects. How do you map a
flat data square that is easy for anyone to edit into these
nested lists and objects?

Solving the challenge

  • Use a key row to name JSON keys
  • Allow data to be stored in row or column orientation.
  • Use javascript notation for keys and arrays
    • Allow dotted key path notation
    • Allow arrays of objects and literals

Excel Data

What is the easiest way to organize and edit your Excel data? Lists of
simple objects seem a natural fit for a row oriented sheets. Single objects
with more complex structure seem more naturally presented as column
oriented sheets. Doesn’t really matter which orientation you use, the
module allows you to speciy a row or column orientation; basically, where
your keys are located: row 0 or column 0.

Keys and values:

  • Row or column 0 contains JSON key paths
  • Remaining rows/columns contain values for those keys
  • Multiple value rows/columns represent multiple objects stored as a list
  • Within an object, lists of objects have keys like phones[1].type
  • Within an object, flat lists have keys like aliases[]

Examples

A simple, row oriented key

firstName
Jihad

produces

[{
  "firstName": "Jihad"
}]

A dotted key name looks like

address.street
12 Beaver Court

and produces

[{
  "address": {
    "street": "12 Beaver Court"
    }
}]

An indexed array key name looks like

phones[0].number
123.456.7890

and produces

[{
  "phones": [{
      "number": "123.456.7890"
    }]
}]

An embedded array key name looks like this and has ‘;’ delimited values

aliases[]
stormagedden;bob

and produces

[{
  "aliases": [
    "stormagedden",
    "bob"
  ]
}]

A more complete row oriented example

firstName lastName address.street address.city address.state address.zip
Jihad Saladin 12 Beaver Court Snowmass CO 81615
Marcus Rivapoli 16 Vail Rd Vail CO 81657

would produce

[{
    "firstName": "Jihad",
    "lastName": "Saladin",
    "address": {
      "street": "12 Beaver Court",
      "city": "Snowmass",
      "state": "CO",
      "zip": "81615"
    }
  },
  {
    "firstName": "Marcus",
    "lastName": "Rivapoli",
    "address": {
      "street": "16 Vail Rd",
      "city": "Vail",
      "state": "CO",
      "zip": "81657"
    }
  }]

You can do something similar in column oriented sheets. Note that indexed
and flat arrays are added.

firstName Jihad Marcus
lastName Saladin Rivapoli
address.street 12 Beaver Court 16 Vail Rd
address.city Snowmass Vail
address.state CO CO
address.zip 81615 81657
phones[0].type home home
phones[0].number 123.456.7890 123.456.7891
phones[1].type work work
phones[1].number 098.765.4321 098.765.4322
aliases[] stormagedden;bob mac;markie

would produce

[
  {
    "firstName": "Jihad",
    "lastName": "Saladin",
    "address": {
      "street": "12 Beaver Court",
      "city": "Snowmass",
      "state": "CO",
      "zip": "81615"
    },
    "phones": [
      {
        "type": "home",
        "number": "123.456.7890"
      },
      {
        "type": "work",
        "number": "098.765.4321"
      }
    ],
    "aliases": [
      "stormagedden",
      "bob"
    ]
  },
  {
    "firstName": "Marcus",
    "lastName": "Rivapoli",
    "address": {
      "street": "16 Vail Rd",
      "city": "Vail",
      "state": "CO",
      "zip": "81657"
    },
    "phones": [
      {
        "type": "home",
        "number": "123.456.7891"
      },
      {
        "type": "work",
        "number": "098.765.4322"
      }
    ],
    "aliases": [
      "mac",
      "markie"
    ]
  }
]

Data Conversions

All values from the ‘excel’ package are returned as text. This module detects numbers and booleans and converts them to javascript types. Booleans must be text ‘true’ or ‘false’. Excel FALSE and TRUE are provided
from ‘excel’ as 0 and 1 — just too confusing.

Caveats

During install (mac), you may see compiler warnings while installing the
excel dependency — although questionable, they appear to be benign.

Running tests

You can run tests after GitHub clone and npm install with:

ᐅ npm run-script test

> excel-as-json@2.0.1 test /Users/starver/code/makara/excel-as-json
> tools/test.sh

  assign
    ✓ should assign first level properties
    ✓ should assign second level properties
    ✓ should assign third level properties
#...

Bug Reports

To investigate bugs, we need to recreate the failure. In each bug report, please include:

  • Title: A succinct description of the failure
  • Body:
    • What is expected
    • What happened
    • What you did
    • Environment:
      • operating system and version
      • node version
      • npm version
      • excel-as-json version
    • Attach a small worksheet and code snippet that reproduces the error

Contributing

This project is small and simple and intends to remain that way. If you want to add functionality, please raise an issue as a place we can discuss it prior to doing any work.

You are always free to fork this repo and create your own version to do with as you will, or include this functionality in your projects and modify it to your heart’s content.

TODO

  • provide processSync — using ‘async’ module
  • Detect and convert dates
  • Make 1 column values a single object?

Change History

2.0.2

  • Fix #23 Embedded arrays contain empty string. Flaw in code inserted empty string when no text values were provided for a key like aliases[].
  • Fix #30 not able to force numbers as strings. Added option convertTextToNumber defaulting to true. If set to false, cells containing text that looks like a number are not converted to a numeric type.

2.0.1

  • Fix creating missing destination directories to complete prior to writing file

2.0.0

  • Breaking changes to most function signatures
  • Replace single option isColOriented with an options object to try to stabilize the processFile signature allowing future non-breaking feature additions.
  • Add sheet option to specify a 1-based index into the Excel sheet collection — all of your data in a single Excel workbook.
  • Add omitEmptyFields option that removes an object key-value if the corresponding Excel cell is empty.

1.0.0

  • Changed process() to processFile() to avoid name collision with node’s process object
  • Automatically convert text numbers and booleans to native values
  • Create destination directory if it does not exist

Сегодня мы разберем этапы создания JSON-объекта из данных excel-файла, загруженного средствами браузера.

Для начала необходимо получить файл excel от пользователя с помощью тега input:

<input type="file" id="fileUploader" name="fileUploader" accept=".xls, .xlsx">

Следующим шагом, нужно определиться, что делать с полученным файлом. Нам потребуется событие change загруженного элемента fileUploader:

$(document).ready(function() {
  $("#fileUploader").change(function(evt) {
    // здесь должен находиться Ваш код
  })
})

Теперь нужно определиться, как именно обработать файл. Для начала, предположим, что клиент загрузил только один файл:

selectedFile = evt.target.files[0];

Затем, мы преобразуем данные файла excel в бинарную строку, используя FileReader. После чего, воспользуемся XLSX, который в свою очередь является встроенным объектом SheetJS js-xlsx, для того, чтобы конвертировать полученную бинарную строку в JSON-объект.

Кстати, нельзя забывать о подключении нужных скриптов в нашем проекте, например так:

<script src="js/jquery.js"> </script>
<script lang="javascript" src="js/xlsx.full.min.js"></script>

И, наконец, наша функция преобразования данных excel-файла в объект JSON:

$(document).ready(function(){
  $("#fileUploader").change(function(evt){
    var selectedFile = evt.target.files[0];
    var reader = new FileReader();
    reader.onload = function(event) {
      var data = event.target.result;
      var workbook = XLSX.read(data,{
        type: 'binary'
      });
      workbook.SheetNames.forEach(function(sheetName){       
        var XL_row_object = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]);
        var json_object = JSON.stringify(XL_row_object);
        document.getElementById("jsonObject").innerHTML = json_object;
      })
    };
    reader.onerror = function(event) {
      console.error("Файл не может быть прочитан. Код ошибки: " + event.target.error.code);
    };
    reader.readAsBinaryString(selectedFile);
  });
});

В результате мы получаем JSON-объект, с данными которого можем продолжить работу.


Полный исходный код можно посмотреть на GitHub.


Спасибо за внимание.


Перевод статьи Yamuna Dulanjani “How to convert Excel data into JSON object using JavaScript”.

Reading Time: 4 minutes

8,649 Views

Inside this article we will see the concept of Upload and Convert Excel file into JSON in javascript. Very easy steps you have to do.

To upload and read excel file in javascript we will use a jquery plugin file. This jquery plugin will read data of excel file row by row. This tutorial will give you the complete detailed concept to use jquery plugin for excel file upload using javascript.

Learn More –

  • How To Integrate CKEditor 4 in HTML And jQuery
  • How to Prevent Styles and JavaScript Files From Cached
  • Javascript Auto Logout in CodeIgniter 4 Tutorial
  • jQuery Datatables Header Misaligned With Vertical Scrolling

Let’s get started.


Sample Excel File

We have taken a sample excel file to see this article from here. We have downloaded 10 rows file from it.

You can go with that link and download it.


Create an Application

Create a folder named as js-excel. Create a file like index.html

Open index.html and write this complete code into it.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Upload And Convert Excel File into JSON in Javascript</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.15.3/xlsx.full.min.js"></script>
  </head>

  <body>

    <div class="container">
        <h4>Upload And Convert Excel File into JSON in Javascript</h4>
        <div class="panel panel-primary">
            <div class="panel-heading">Upload And Convert Excel File into JSON in Javascript</div>
            <div class="panel-body">
                <!-- Input type file to upload excel file -->
                <input type="file" id="fileUpload" accept=".xls,.xlsx" /><br />
                <button type="button" id="uploadExcel">Convert</button>

                <!-- Render parsed JSON data here -->
                <div style="margin-top:10px;">
                    <pre id="jsonData"></pre>
                </div>
            </div>
        </div>
    </div>
    
    <script>
        var selectedFile;
        document
          .getElementById("fileUpload")
          .addEventListener("change", function(event) {
            selectedFile = event.target.files[0];
          });
        document
          .getElementById("uploadExcel")
          .addEventListener("click", function() {
            if (selectedFile) {
              var fileReader = new FileReader();
              fileReader.onload = function(event) {
                var data = event.target.result;
    
                var workbook = XLSX.read(data, {
                  type: "binary"
                });
                workbook.SheetNames.forEach(sheet => {
                  let rowObject = XLSX.utils.sheet_to_row_object_array(
                    workbook.Sheets[sheet]
                  );
                  let jsonObject = JSON.stringify(rowObject);
                  document.getElementById("jsonData").innerHTML = jsonObject;
                  console.log(jsonObject);
                });
              };
              fileReader.readAsBinaryString(selectedFile);
            }
          });
      </script>
  </body>
</html>

xlsx.full.min.js -> javascript library for excel upload


Application Testing

Open browser and type this –

URL – http://localhost/js-excel/index.html

We hope this article helped you to learn Upload And Convert Excel File into JSON in Javascript Tutorial in a very detailed way.

Buy Me a Coffee

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Понравилась статья? Поделить с друзьями:
  • Java read string word by word
  • Java read from file word by word
  • Java poi excel html
  • Java parse excel file
  • Java library for excel