Скрипт excel в json

excel2json

Copyright (C) 2013 by Hojin Choi hojin.choi@gmail.com

Excel2json is a converting script that supports to manage well structured excel data to json format.

You can freely redistribute this product with A-CUP-OF-BEER License (See source code)

USAGE

ADD SOME HINTS TO YOUR EXCEL FILE FOR JSON

There are four types of object, which can be handled by this script.

Simple Object

If you have an excel file, very simple one like this.

A B C D E
1 Initial data
2 Name Value
3 coins 1000
3 golds 0

And, Let’s give a hint for the script, which awares A Column’s ‘#’ mark.

A B C D E
1 Initial data
2 Name Value
3 #initdata{} $key $value inserted!
4 coins 1000
5 golds 0

In the above example, you can get this JSON file

{
	"initdata" : {
		"coins" : 1000,
		"golds" : 0
	}
}

Objects in Object

Above example explains plain value object, now if you want an object which
has objects as the key/value pairs, you can use «{{}}» suffix instead of «{}»

A B C D E
1 Buildings
2 Name Color Width Height
3 #buildings{{}} $key color width height
4 barrack blue 200 200
5 mine yellow 200 100
6 gas red 100 100
7 townhall black 200 200

And, this yields

{
	"buildings" : {
		"barrack" : {
			"color": "blue",
			"width": 200,
			"height": 200
		},
		"mine" : {
			"color": "yellow",
			"width": 200,
			"height": 100
		},
		"gas": {
			"color": "red",
			"width": 100,
			"height": 100
		},
		"townhall": {
			"color": "black",
			"width": 200,
			"height": 100
		}
	}
}			

Arrays in Object

This type of object has nested value as an array, see this example!

A B C D E
1 Required coins of buildings
2 #reqcoins{[]} barrack mine gas
3 100 100 100
4 500 500 500
5 1000 1000 1000
6 1500

As you can see, the suffix of #reqcoins is «{[]}», this gives hints for constructing vertical array.
The result is

{
	"reqcoins" : {
		"barrack" : [100, 500, 1000, 1500 ],
		"mine" : [ 100, 500, 1000 ],
		"gas"  : [ 100, 500, 1000 ]
	}
}

Object Array

The last format of compound data is an array which contains objects, the suffix «[{}]»

A B C D E
1 Shop
2 #shop[{}] name price category
3 blade 100 attack
4 dagger 200 attack
5 shield 100 defese

And this yields

{
	"shop" : [
		{
			"name": "blade",
			"price" : 100,
			"category" : "attack"
		},
		{
			"name": "dagger",
			"price": 200,
			"category": "attack"
		},
		{
			"name": "shield",
			"price": 100,
			"category": "defense"
		}
	]
}

Array Value (Tip)

Magic field suffix «[]» of object description line introduce array value.

A B C D E
1 Shop
2 #inventory[{}] type attrib[] dur
3 blade oil, diamond 100
4 dagger sapphire 150
5 shield diamond,sapphire,rune 200

The «attrib[]» field name terminates with «[]», which indicates attrib key has
array value. so, the result will be like this.

{
	"inventory" : [
		{
			"type": "blade",
			"attrib": [ "oil", "diamond" ],
			"dur": 100
		},
		{
			"type": "dagger",
			"attrib": [ "sapphire" ],
			"dur": 150
		},
		{
			"type": "shield",
			"attrib": [ "diamond", "sapphire", "rune" ],
			"dur": 200
		}
	]
}

Some technical marks

‘!’ prefixed sheet name

You can insert ‘!’ mark before a sheet name which will not be considered to be parsed. For e.g. ‘!Samples’, ‘!Test’ or ‘!Templates’.

RUN Excel2Json.js

«.js» extension files are associated with WSCRIPT.EXE (Windows already has this program!),
you can easily run the script by double click!

You may also make your own start script, like an ‘excel2json.bat’ with which you can run the script
specifying excel files and output folder name as the arguments.

MKDIR output
WSCRIPT.EXE Excel2Json.js file1.xlsx file2.xlsx product

HOWTO-WORK

Internally, CSV format is used to parse excel files.

By clicking the script in explorer:

0. Make 'output' folder (mkdir output)
1. Run the script in a folder without any argument (by clicking)
2. The script searches the folder for all excel files with extension .xls, .xlsx.
3. All the sheets in the excel file are converted to CSV files.
4. The CSV files are stored temporary folders with suffix (.$$$)
6. Parse the CSV files and make json files into the 'output' folder.
7. All the temporary folders will be removed with their contents (csv files)

By running WSCRIPT.EXE Excel2Json.js file1.xlsx file2.xlsx product:

1. All the proceess is same with above.
2. But it does not search the directory for excel files.
3. And use the 'product' directory instead of 'output' for its result.

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

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.

Reading Time: 4 minutes

8,651 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.

Ludivine A

Ludivine A

Posted on Dec 15, 2021

• Updated on Dec 21, 2021



 



 



 



 



 

 

Do you need to get data from a spreadsheet and turn it into a JSON ? That’s not 🚀 science and I’m gonna prove it !

First, install the xlsx package.

With npm :

// NPM
npm  install  xlsx

// Yarn
yarn  add  xlsx

Enter fullscreen mode

Exit fullscreen mode

In the app.js file, import xlsx and fs to read the excel file, and declare a variable that we will use later.

const XLSX = require('xlsx');
const fs = require('fs');
const finalObject = {};

Enter fullscreen mode

Exit fullscreen mode

To read and get the content of the file with the Buffer type :

const data = XLSX.read(myFile, { type: 'buffer' });

Enter fullscreen mode

Exit fullscreen mode

N.B: The different types are «string», «buffer», «base64», «binary», «file», «array»

If you write console.log(data.Sheet) you will see your spreadsheets and the cells content.

Then you have to write the process for each row of each spreadsheet.

data.SheetNames.forEach(sheetName => {
  let rowObject = XLSX.utils.sheet_to_json(data.Sheets[sheetName]);

  finalObject[sheetName] = rowObject;
});

Enter fullscreen mode

Exit fullscreen mode

The sheet_to_json function allows to convert a spreadsheet into an array of objects.
It takes differents optionnal parameters that you can find here
Here we won’t need anything

If you do a console.log(rowObject), you will see that it contains an array, and each row of the spreadsheet is turned into an object like so :

[
  { "ID": 1, "Last name": "Doe", "First name": "John" },

  { "ID": 2, "Last Name": "Doe", "First name": "Jane" }
]

Enter fullscreen mode

Exit fullscreen mode

Do you remember the variable we declared at the beginning ? It is time to use it. We are going to create a key for each spreadsheet and assign rowObject to it :

data.SheetNames.forEach(sheetName => {
  let rowObject = XLSX.utils.sheet_to_json(data.Sheets[sheetName]);

  finalObject[sheetName] = rowObject;
});

Enter fullscreen mode

Exit fullscreen mode

If you console.log(finalObject) :

"Utilisateurs": [
{ "ID": 1, "Last name": "Doe", "First name": "John" },
{ "ID": 2, "Last name": "Doe", "First name": "Jane" }
]

Enter fullscreen mode

Exit fullscreen mode

If you want to write the output into a file, simply add this line :

fs.writeFileSync('./target.json', JSON.stringify(dataObject));

Enter fullscreen mode

Exit fullscreen mode


Voilà 🎉
Now you know how to convert an Excel spreadsheet into JSON !


Originally posted on my blog. Check out my instagram account to learn more about web development.

Понравилась статья? Поделить с друзьями:
  • Скриншоты работы в word
  • Скриншот таблицы excel в word
  • Скриншот преобразовать в документ word
  • Скриншот в word онлайн
  • Скрин выделенной области в excel