Excel to json макрос

convert json to excel

24 Aug Convert Excel to JSON Using VBA

Posted at 02:58h
in Excel VBA
2 Comments

Howdee! I had a lot of requests after my recent article on converting a JSON string to Excel, asking if it was possible to convert Excel to JSON. Fortunately, it is not only possible, but you can use the same library we previously covered to do so! In this article, we will go over how to convert your Excel data to a JSON string, and how to convert that same data to a JSON file. If you haven’t read the previous article linked above, I highly recommend you do so before reading on here. Beyond covering how to import JSON, it also covers the basics of JSON objects and arrays. With that said, let’s dive in!

Convert Excel to JSON String

The most common occurrence for me, is the need to transfer some sort of data from an Excel file to a JSON string so I can pass that information through a HTTP request or to another program. For this, you’ll need to convert Excel to JSON, and store that in a variable. To do that, we need to dimension a few variables to use later:

Dim excelRange As Range
Dim jsonItems As New Collection
Dim jsonDictionary As New Dictionary
Dim i As Long
Dim cell As Variant

The first variable, excelRange, will be used to define the range of data we want to convert to JSON. The second, jsonItems, will be the collection we ultimately store our data in. Collection might be a new term to some so, at a high level, a collection is just an object that we can use to group and manage related objects. The third variable, jsonDictionary, is the dictionary we will first store our Excel values in. A dictionary is a type of collection that you can access using a key. Again, check out the previous post on JSON to get a better understanding of this type of object. The last two variables, i & cell, will be used in our for loop to help store the values to a dictionary. The next bit of our code looks like this:

Set excelRange = Cells(1, 1).CurrentRegion

For i = 2 To excelRange.Rows.Count
    jsonDictionary("id") = Cells(i, 1)
    jsonDictionary("name") = Cells(i, 2)
    jsonDictionary("username") = Cells(i, 3)
    jsonDictionary("email") = Cells(i, 4)
    jsonDictionary("street") = Cells(i, 5)
    jsonDictionary("suite") = Cells(i, 6)
    jsonDictionary("city") = Cells(i, 7)
    jsonDictionary("zipcode") = Cells(i, 8)
    jsonDictionary("phone") = Cells(i, 9)
    jsonDictionary("website") = Cells(i, 10)
    jsonDictionary("company") = Cells(i, 11)

    jsonItems.Add jsonDictionary
    Set jsonDictionary = Nothing
Next i

MsgBox JsonConverter.ConvertToJson(jsonItems, Whitespace:=3)

So what is happening here? Firstly, I start by setting the range where our data exists. Now that I know the size of the range, I can begin to convert Excel to JSON by looping through each row (skipping headers) and writing each cell’s value into the dictionary. At the end of each loop, I need to write the dictionary to my collection and then clear it for the next loop. Lastly, I’m printing this JSON string to a message box so we can view it. You can do whatever you wish with the JSON string at this point, I’m only printing to a message box to demonstrate how to convert Excel to JSON string.

excel to json

Convert Excel to JSON File

Converting Excel data to a JSON file is almost the exact same process. The only difference is, instead of outputting the result to a string variable or writing it to a cell in the workbook, you’re going to use the FileSystemObject model to create a new file to convert & store Excel data to a JSON file. You’ll need these two new variables:

Dim jsonFileObject As New FileSystemObject
Dim jsonFileExport As TextStream

The first allows you to access the FileSystemObject model which will allow you to create new files and save them to a folder. The second allows you to write text, in this case the JSON string, to the file. Those two new lines of code look like this:

Set jsonFileExport = jsonFileObject.CreateTextFile("C:UsersusernameDesktopjsonExample.json", True)
jsonFileExport.WriteLine (JsonConverter.ConvertToJson(jsonItems, Whitespace:=3))

The first will create the new JSON file. Make sure you use the keyword “True” if you’re planning to reuse this code. This will allow the program to overwrite the file. However, if you’re having the user create the name of the file, it might be useful to use “False” which will not allow the program to create any new file that would overwrite a previous one.

The second line of code simply writes the converted JSON to the file. Unless you open the file in your code, there is no need to explicitly save or close the file in this example. The full code to convert Excel to JSON looks like this:

Sub excelToJsonFileExample()
Dim excelRange As Range
Dim jsonItems As New Collection
Dim jsonDictionary As New Dictionary
Dim jsonFileObject As New FileSystemObject
Dim jsonFileExport As TextStream
Dim i As Long
Dim cell As Variant

Set excelRange = Cells(1, 1).CurrentRegion

For i = 2 To excelRange.Rows.Count
    jsonDictionary("id") = Cells(i, 1)
    jsonDictionary("name") = Cells(i, 2)
    jsonDictionary("username") = Cells(i, 3)
    jsonDictionary("email") = Cells(i, 4)
    jsonDictionary("street") = Cells(i, 5)
    jsonDictionary("suite") = Cells(i, 6)
    jsonDictionary("city") = Cells(i, 7)
    jsonDictionary("zipcode") = Cells(i, 8)
    jsonDictionary("phone") = Cells(i, 9)
    jsonDictionary("website") = Cells(i, 10)
    jsonDictionary("company") = Cells(i, 11)

    jsonItems.Add jsonDictionary
    Set jsonDictionary = Nothing
Next i

‘change the path below to save where you desire
Set jsonFileExport = jsonFileObject.CreateTextFile("C:UsersusernameDesktopjsonExample.json", True)
jsonFileExport.WriteLine (JsonConverter.ConvertToJson(jsonItems, Whitespace:=3))

End Sub

Here is the outputted JSON file displayed in Visual Studio Code:

convert excel to json

I hope this tutorial was useful for those of you that need to write your Excel data to JSON either to a string or to a file. If you have questions, drop them in the comments below. As always, the example file is available for your download if you’re a registered member to this site. The file contains the examples I walked through today to convert Excel to JSON. Registering is free and only takes a minute. You’ll get notified as I release additional content but I won’t spam you with tons of unsolicited emails. Until next time!

Cheers,

R

VBA-Excel-Table-To-JSON

What is this?

A small VBA script that converts Excel tables to JSON format and exports the data to a .json file at the location of your choice. Use the script by importing the .bas and .frm & .frx files to your Excel VBA editor.

Installation

You can use this script by following these steps:

  1. Open up Microsoft Excel
  2. Go to the Developer tab (For more information on how to show the developer tab, go here)
  3. Click on Visual Basic, in the upper left corner of the window
  4. In the toolbar at the top of the window that appears, click on file 👉 Import file…
  5. Select ExcelToJSON.bas and click on Open
  6. Click on file 👉 Import file… for a second time
  7. Select ExcelToJSONForm.frm and click on Open (make sure that ExcelToJSONForm.frx is located in the same folder, or this step will not work)
  8. Congratulation, you have successfully installed the script 🎉🥳

Usage

To use the script, you need an Excel file with at least one table in it. Once you do, follow these instructions:

  1. Go to the Developer tab
  2. Click on Macros
  3. Select PERSONAL.XLSB!ExcelToJSON.ExcelToJSON
  4. Click on Run
  5. In the window that appears, select which tables that you would like to export, and then click on Submit
  6. Finally select the name for the JSON file that will be selected as well as the location that you would like to save the file in

Please note that the script ‘escapes’ all double quotes that exists in the table cells to stay compatible with the JSON format. This means that a cell that contains the text Lorem ipsum "dolor sit" amet, consectetur will be edited to look like Lorem ipsum "dolor sit" amet, consectetur.

The script prints out the cell values of all cell contents as strings, and will not print out the formulas used

The script does not support unicode characters yet, but this will be implemented in a future version.

Contact

You can reach me at otto[dot]wretling[at]gmail[dot]com

License

MIT License

Copyright (c) 2020 theAwesomeFufuman

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
«Software»), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED «AS IS», WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Excel to JSON using Excel VBA

JSON format data is widely popular when it comes to send and receive information between a web server and a client. I bumped into a situation where I needed to do the POST to my server and obviously the data format I needed was in JSON. So, I wrote this little Excel VBA macro to convert a given range into a JSON format.

Excel Macro to convert given range to JSON format

Public Function ToJSON(rng As range) As String
‘ Make sure there are two columns in the range
If rng.Columns.Count < 2 Then
ToJSON = CVErr(xlErrNA)
Exit Function
End If

Dim dataLoop, headerLoop As Long
‘ Get the first row of the range as a header range
Dim headerRange As range: Set headerRange = range(rng.Rows(1).Address)

‘ We need to know how many columns are there
Dim colCount As Long: colCount = headerRange.Columns.Count

Dim json As String: json = «[»

For dataLoop = 1 To rng.Rows.Count
‘ Skip the first row as it’s been used as a header
If dataLoop > 1 Then
‘ Start data row
Dim rowJson As String: rowJson = “{”

‘ Loop through each column and combine with the header
For headerLoop = 1 To colCount
rowJson = rowJson & “””” & headerRange.Value2(1, headerLoop) & “””” & “:”
rowJson = rowJson & “””” & rng.Value2(dataLoop, headerLoop) & “”””
rowJson = rowJson & “,”
Next headerLoop

‘ Strip out the last comma
rowJson = Left(rowJson, Len(rowJson) – 1)

‘ End data row
json = json & rowJson & “},”
End If
Next

‘ Strip out the last comma
json = Left(json, Len(json) – 1)

json = json & “]”

ToJSON = json
End Function

So I would pass in the range to a JavaScript function and let it iterate over the Excel object model and build the array in JavaScript. Then call a JavaScript library to convert array into a string (hat tip Douglas Crockford) and simply return the string to VBA. So no string operations in VBA.

The JavaScript function is given below but depends upon Douglas Crockford’s library at https://raw.githubusercontent.com/douglascrockford/JSON-js/master/json2.js. Save this in a file and then amend VBA code with the correct file path so the JavaScript is loaded into the Microsoft Script Control.

function ExcelTableToJSON(rngTable) {
    try {
        if (rngTable && rngTable['Rows'] && rngTable['Columns']) {
            var rowCount = rngTable.Rows.Count;
            var columnCount = rngTable.Columns.Count;
            var arr = new Array();

            for (rowLoop = 1; rowLoop <= rowCount; rowLoop++) {
                arr[rowLoop - 1] = new Array();
                for (columnLoop = 1; columnLoop <= columnCount; columnLoop++) {
                    var rngCell = rngTable.Cells(rowLoop, columnLoop);
                    var cellValue = rngCell.Value2;
                    arr[rowLoop - 1][columnLoop - 1] = cellValue;
                }
            }
            return JSON.stringify(arr);
        }
        else {
            return { error: '#Either rngTable is null or does not support Rows or Columns property!' };
        }
    }
    catch(err) {
        return {error: err.message};
    }
}

The Excel VBA code is thus

Option Explicit

'In response to
'http://stackoverflow.com/questions/38100193/is-it-possible-in-vba-convert-excel-table-to-json?rq=1
'Is it possible in VBA convert Excel table to json

'Tools->References->
'Microsoft Script Control 1.0;  {0E59F1D2-1FBE-11D0-8FF2-00A0D10038BC}; C:WindowsSysWOW64msscript.ocx

Private Sub Test()

    Dim oScriptEngine As ScriptControl
    Set oScriptEngine = New ScriptControl
    oScriptEngine.Language = "JScript"

    oScriptEngine.AddCode GetJavaScriptLibraryFromWeb("https://raw.githubusercontent.com/douglascrockford/JSON-js/master/json2.js")

    Dim sJavascriptCode As String
    sJavascriptCode = CreateObject("Scripting.FileSystemObject").GetFile("<<<Your file path to javascript file>>>ExcelTableToJSON.js").OpenAsTextStream.ReadAll

    oScriptEngine.AddCode sJavascriptCode

    Dim rngTable As Excel.Range
    Set rngTable = ThisWorkbook.Worksheets.Item("Sheet2").Range("A1:B2")

    rngTable.Cells(1, 1) = 1.2
    rngTable.Cells(1, 2) = "red"
    rngTable.Cells(2, 1) = True
    rngTable.Cells(2, 2) = "=2+2"


    Dim sStringified As String
    sStringified = oScriptEngine.Run("ExcelTableToJSON", rngTable)
    Debug.Assert sStringified = "[[1.2,""red""],[true,4]]"

    Stop

End Sub

Public Function GetJavaScriptLibraryFromWeb(ByVal sURL As String) As String

    Dim xHTTPRequest As Object 'MSXML2.XMLHTTP60
    Set xHTTPRequest = VBA.CreateObject("MSXML2.XMLHTTP.6.0")
    xHTTPRequest.Open "GET", sURL, False
    xHTTPRequest.send
    GetJavaScriptLibraryFromWeb = xHTTPRequest.responseText

End Function

Содержание

  1. Вывод табличных данных Excel в виде JSON для использования в Power Automate
  2. Пример файла Excel
  3. Пример кода: возврат данных таблицы в формате JSON
  4. Пример выходных данных на листе PlainTable
  5. Пример кода: возврат данных таблицы в формате JSON с текстом гиперссылки
  6. Пример выходных данных на листе WithHyperLink
  7. Использование в Power Automate
  8. Is it possible in VBA convert Excel table to json
  9. 2 Answers 2
  10. Linked
  11. Related
  12. Hot Network Questions
  13. Subscribe to RSS
  14. Save Excel Table to JSON File using VBA and VBA-JSON
  15. Step 1: Setup VBA-JSON and Add References
  16. Step 2: The code
  17. 13 thoughts on “Save Excel Table to JSON File using VBA and VBA-JSON”
  18. How to convert Excel to JSON?
  19. Why Excel to JSON?
  20. Tip: WTSolution Excel to JSON Converter is also known as Excel to JSON add-in. Microsoft offers this tool.
  21. Altova MapForce
  22. White Town xls to JSON converter
  23. Oxygen JSON Editor
  24. WTSolution Excel to JSON converter
  25. Excel to JSON add-in
  26. Requirement
  27. Limitation
  28. Row conversion
  29. Nested conversion
  30. Download add-in
  31. Tip: The fields that are marked with * sign are required fields and others are optional.
  32. Note: The Excel file, which is currently opened, is read-only that contains a few instructions about this tool. Hence, open the targeted file first, which you want to convert Excel to JSON.
  33. Tip: While using this add-in to convert your data, your system must be connected to the internet. Otherwise, you may face problems.
  34. Excel to JSON using VBA code editor
  35. Tip: Your Excel data must have column names because the first row is always considered as a header.
  36. VBA Code
  37. Feedback
  38. Help Others, Please Share
  39. Learn Latest Tutorials
  40. Preparation
  41. Trending Technologies
  42. B.Tech / MCA
  43. Javatpoint Services
  44. Training For College Campus

Вывод табличных данных Excel в виде JSON для использования в Power Automate

Данные таблицы Excel можно представить в виде массива объектов в формате JSON. Каждый объект представляет строку в таблице. Это помогает извлекать данные из Excel в согласованном формате, который виден пользователю. Затем данные могут быть переданы другим системам с помощью потоков Power Automate.

Пример файла Excel

Скачайте файлtable-data-with-hyperlinks.xlsx для готовой к использованию книги.

Вариант этого примера также включает гиперссылки в одном из столбцов таблицы. Это позволяет отображать дополнительные уровни данных ячейки в ФОРМАТЕ JSON.

Пример кода: возврат данных таблицы в формате JSON

Добавьте следующий скрипт, чтобы попробовать пример самостоятельно!

Структуру можно изменить в interface TableData соответствии со столбцами таблицы. Обратите внимание, что для имен столбцов с пробелами обязательно поместите ключ в кавычки, например в «Event ID» примере. Дополнительные сведения о работе с JSON см. в статье Использование JSON для передачи данных в скрипты Office и из нее.

Пример выходных данных на листе PlainTable

Пример кода: возврат данных таблицы в формате JSON с текстом гиперссылки

Скрипт всегда извлекает гиперссылки из 4-го столбца (индекс 0) таблицы. Вы можете изменить этот порядок или включить несколько столбцов в качестве данных гиперссылки, изменив код в примечании. // For the 4th column (0 index), extract the hyperlink and use that instead of text.

Пример выходных данных на листе WithHyperLink

Использование в Power Automate

Сведения об использовании такого сценария в Power Automate см. в статье Создание автоматизированного рабочего процесса с помощью Power Automate.

Источник

Is it possible in VBA convert Excel table to json

I need convert data from excel table with about twenty columns and a lot of rows into json. I don’t found a short example of code for this purpose in vba. I found this one https://github.com/VBA-tools/VBA-JSON/blob/master/JsonConverter.bas , but it is very large. May be it is a shorter example?

2 Answers 2

if you want to write it to file there’s a code:

So I would pass in the range to a JavaScript function and let it iterate over the Excel object model and build the array in JavaScript. Then call a JavaScript library to convert array into a string (hat tip Douglas Crockford) and simply return the string to VBA. So no string operations in VBA.

The JavaScript function is given below but depends upon Douglas Crockford’s library at https://raw.githubusercontent.com/douglascrockford/JSON-js/master/json2.js. Save this in a file and then amend VBA code with the correct file path so the JavaScript is loaded into the Microsoft Script Control.

The Excel VBA code is thus

Linked

Hot Network Questions

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.3.17.43323

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Save Excel Table to JSON File using VBA and VBA-JSON

While importing JSON files to an Excel Table is easy using a Get and Transform query, going the other way and saving an Excel table as a JSON file is unfortunately not as simple. Luckily, with the code below, it’s easy to save the first Excel table in your sheet as a JSON file.

Step 1: Setup VBA-JSON and Add References

First, download VBA-JSON. Follow the instructions on the GitHub page to install. In essence, use File > Import File to import. Ensure you have a reference to Microsoft Scripting Runtime as shown below.

Adding a reference to the Microsoft Scripting Runtime. You can access this from Tools > References.

Step 2: The code

In my case I chose to place the code inside a function which is called upon button click, but you could use another method of activation. When called, this function prepares the JSON and then opens a save window to save the sheet as a JSON file. It will be saved as an array containing objects with the header row items as properties.

That’s it! I hope you find this tutorial useful.

13 thoughts on “Save Excel Table to JSON File using VBA and VBA-JSON”

hi thanks a lot so simple but please let me know code to generate json with telugu text from excel,

Interesting article, thank you for sharing it. It’s a good approach for Excel and json conversion. I have found also this solution on the internet https://dev-bay.com/json-to-excel/ which also works good – but here one question about that, is it a good approach to flatter JSON like this tool does?

This code works really well, but I’m running into issues with large amounts of data. Are there limitations on file size or numbers of rows in an Excel file?

Hi. When I try to convert Dates into JSON, it returns output based on UTC time.
For example: I am in Eastern time Canada. I converted dates that were in ET but the output came out as UTC time. So the values are different than what was there eon the excel file. Was this a conscious effort?

Generally that is how Excel stores dates. I’m surprised you got a formatted date at all, and not just an integer timestamp to be honest. I don’t see any option in VBA-JSON to address that so you could play around with Excel but this may be something you need to run another script on your output on to fix. I don’t have experience using this with dates unfortunately.

I am not sure what I am doing wrong but I followed everything to a T and I get a ;

Run-time error ‘9’: Subscript out of range

For Each c In ActiveSheet.ListObjects(1).HeaderRowRange.Cells

Is highlighted in Yellow.

Any idea what I could be doing wrong?

Using Microsoft® Excel® for Microsoft 365 MSO (16.0.14228.20200) 32-bit

Are you certain that your data is formatted as part of an Excel table? If not, you will have to convert it to a table first. Otherwise, you won’t have any list objects, meaning it can’t find list object one.

Hii Do you get any solution for this, i am also stuck in these same

You need your data to be in a table. Go to insert -> table -> select the area with your data and click ok. Try generating the Json again. It should work.

How should string data be expressed in an Excel cell so that it is output as a JSON array?

This was very helpful thank you. I would like to add to my code though. How would I be able to convert the hyperlinks in my excel file through VBA to have them be a part of my JSON?

Great tutorial. Really loved the micro explanations everywhere. Helps people like myself who learned via sink or swim.

I am trying to do a very specific thing… export to nested json. The output is very specific (NFT metadata) and requires a list of attributes to be an defined array of names and values. It’s something like this:

Then that row would need to be exported as its own json file using a leading zeros format based on the ID column.

The only successful implementation I have seen (without multiple file export) was NiftyKit’s done in Google Sheets with gs code, but gs (and JS derivatives in general) doesn’t convert well to vba for use with my data. They use dots in the header row to signify how to nest the data. For instance, “attributes.0.name” defines “name” in the 0th array of attributes… <…”attributes”:[…<…”name”:”_NAME_”…>_(=[0])…]…>

I’m not sure if the library is set up to handle that sort of mess, but if you could point me the right functions to use, that would be helpful. For more I formation on this style of metadata, check out OpenSea’s docs on the topic.

As far as I know you can create that JSON structure in VBA and then just use ConvertToJson on it. If you aren’t sure how to represent it in VBA, write a mock JSON first with the format you want, import it using the same library, and check how it represented it.

Tough part here is probably representation in Excel. Sometimes you would need multiple tables to represent data like this. Another way to go about it, which is essentially a one-to-many relationship is just to duplicate the data in the table. So Title, description, name, value, etc is all a column and title is just re-printed for each row. Best of luck.

Источник

How to convert Excel to JSON?

The users have different requirements, e.g., convert the excel data to JSON format. It needs to do the mapping of Excel worksheet columns to object keys. An Excel to JSON converter helps to convert the .xls file data to .JSON file format.

These Excel files can contain text, charts, graphs, formatting, functions, and more data.

There is no predefined method in Excel to convert the Excel data to JSON. You can either use online Excel to JSON conversion software or download an add-in from the Microsoft store for this task to get done.

Why Excel to JSON?

Excel files are heavy weighted files that may contain text, charts, graphs, formatting, functions, and more data.

While the JSON files are light-weighted text-based documents. It stores the data in a simple data structure. Hence, JSON files can be opened on any text software like Notepad or Wordpad.

There are several tools available to convert the Excel data to JSON.

  1. Altova MapForce
  2. White Town XLS to JSON Converter
  3. Oxygen JSON Editor
  4. WTSolution Excel to JSON Converter

Here, we will brief about these tools with their download links.

Tip: WTSolution Excel to JSON Converter is also known as Excel to JSON add-in. Microsoft offers this tool.

For the last tool — Excel to JSON, we will also show you the steps to download and use this software.

Altova MapForce

Altova MapForce is a data mapping and conversion tool as well. It is a useful software to convert various sets of data. Using this tool, you can convert the Excel data to JSON, XML to JSON, and vice versa.

IMAGE

Additionally, this tool also allows the users to convert the JSON to CSV, EDI, Google protocol buffer, and more. This tool is easy to use as it provides a drag and drop interface. It also supports advanced data processing.

Altova MapForce is not free software but comes with 30 days of a free trial. Download the Altova MapForce tool from the following link.

White Town xls to JSON converter

This software is an xls to JSON converter. As the name implies, it allows the users to convert the Excel data into JSON format. However, it only allows the Excel data to be changed into JSON format. This software supports both formats (.xls and .xlsx formats) of Excel.

IMAGE

One of the biggest advantages of using this software, it is free of cost. Although you can also buy the personal or business license of it. It is very easy to use that is why it is very popular, mostly for those who transfer their data online.

You can download the White Town xls to JSON converter tool from the following link.

Oxygen JSON Editor

Oxygen JSON Editor is software used to convert the Excel file data to JSON format by mapping the Excel columns to JSON object key. This software is complex software than the other ones we have described above.

As Oxygen JSON Editor is a complex software, it has complex features too. Complex features, such as — structure validation, indent, format, and content completion. Additionally, this software also allows us to convert the XML document to JSON format.

IMAGE

Oxygen JSON Editor works differently than the other Excel to JSON converters. It uses XSLT stylesheet template for the conversion. Most professionals prefer this software to convert their data. It is a paid software whose personal, business, and academic versions are available on its official website.

Check out its official site to download the Oxygen JSON Editor.

WTSolution Excel to JSON converter

This one is the last Excel to JSON converter of this chapter by using which one can perform Excel to JSON conversion on their data. It is a simple application for this task to perform. This software supports two types of conversions on Excel data: Row and Nested.

You have also listened its name as Excel to JSON add-in. Microsoft offers this add-in named Excel to JSON that helps the users to convert their Excel data into JSON format. Now, let’s know something about Excel to JSON add-in and also see the downloading steps for it.

Excel to JSON add-in

Excel to JSON is an add-in offered by Microsoft to convert the Excel sheet data to JSON format. When the data is converted to the JSON format, Excel sheet columns are changed to object keys in JSON. It costs no charge from the user to download and use it.

You can download this add-in from the Office store.

Requirement

Excel to JSON add-in will work only on Excel 2013 or higher versions. Hence, your Excel version must be 2013 or higher.

Limitation

This add-in has a limitation.

It can convert the selected Excel data to JSON format.

Currently, two types of conversions are supported by this add-in.

Row conversion

In row type conversion, the first row is treated as header, and rest of the rows are interpreted as data.

Nested conversion

In nested type conversion, you can define a JSON schema. This add-in will do the conversion accordingly, the schema you have provided.

Download add-in

Excel to JSON add-in is available in Office store; you can download it from there. For step by steps learning, follow this chapter below —

Step 1: Download the Excel to JSON add-in from the following link.

Step 2: A webpage of the Office store will open, where click on the Get it now button.

Step 3: Before start downloading, it will ask you to log in to your Microsoft account with valid credentials.

If you do not have a Microsoft account, signup for free to create new account.

Step 4: When you login to your Microsoft account. It will ask for some basic information required by this app before download. Here, provide these details and click the Continue button.

Tip: The fields that are marked with * sign are required fields and others are optional.

Step 5: Now, click the Open in Excel button here.

If you don’t have any MS Excel 2013 or above version downloaded in your system, you can go for office online. By clicking on this link.

We have clicked on the Open in Excel.

Step 6: On this popup, leave the checkbox unmarked and click on Open Excel here.

Step 7: Your Excel will be opened on your system, but it requires an internet connection. If it is not available, you may get this type of warning error.

Step 8: When you click on OK, it will show you one more panel that shows you some reason why this error can occur. This error can be because of the following reasons.

So, connect your system with the internet and close the currently opened Excel workbook.

Step 9: Follow Step 5 and step 6 again, where click on the Open the Excel button.

This time your system is connected to the internet. So, it will not show any error and interruption while installing the add-in.

Step 10: An interface on the Excel file will open like this with Excel to JSON add-in. Now, add this add-in to your Excel tab by clicking on Trust this add-in button present on the right panel.

Step 11: Excel to JSON add-in is successfully added to the Excel ribbon as a tab in the end. See here —

Step 12: Your Excel to JSON add-in is ready to launch. It is available inside the Excel-to-JSON tab by the name Launch Excel-to-JSON button.

Note: The Excel file, which is currently opened, is read-only that contains a few instructions about this tool. Hence, open the targeted file first, which you want to convert Excel to JSON.

Step 13: Prepare a new Excel sheet or open that one whose data you want to change in format. We have opened an existing file of person details and click on the Launch Excel-to-JSON button.

Step 14: Once you click on it, you may get this error. Ignore it and click OK to move forward.

Tip: While using this add-in to convert your data, your system must be connected to the internet. Otherwise, you may face problems.

Step 15: Now, select at least first two row’s data or all where first one is considered as header and the other as data. Then click on GO in the right panel.

Step 16: You will see that the selected data is converted into JSON format and available below the Go button.

Step 17: Copy this data from here, paste this JSON data into a file and save it. Hence, click on the Copy to clipboard button here.

Step 18: JSON data is successfully copied to the clipboard.

Step 19: Now, paste this copied clipboard data to a Word file and save it. The copied data will look like as shown below —

Excel to JSON using VBA code editor

Besides using all these tools, you can use the in-built feature of Excel (VBA code editor) to convert the Excel data to JSON format. Make a code for it and execute the code; it will do the mapping of Excel columns to JSON object keys and convert the data into JSON.

If you are comfortable in doing coding, then it’s a good way for you. Thus, you do not need to explicitly download the above discussed tools to convert your Excel data to JSON format. While you can do it without downloading any software on your system using Excel VBA code Editor.

Tip: Your Excel data must have column names because the first row is always considered as a header.

VBA Code

Following is the complete code for the conversion of the Excel file data to JSON format. Copy this following code and paste this to your respective VBA code editor.

In this VBA code, we have defined a function named ExcelToJSON that will later be used in an Excel file for converting Excel data to JSON format. Let’s see how it will execute.

Syntax

Now, go back to the Excel file and write the following ROUND() formula in an Excel cell where you want to place the converted JSON result. For example,

Currently, we are converting the first two Excel rows data into JSON format only.

Press the Enter key and get the result and see that the data is successfully converted into JSON form. Similarly, you can use this function for more conversion.

For the detailed description of this code, see our next tutorial, where we have explained this code and variables created and used in it.

Feedback

Learn Latest Tutorials

Python Design Patterns

Preparation

Trending Technologies

B.Tech / MCA

Javatpoint Services

JavaTpoint offers too many high quality services. Mail us on [email protected], to get more information about given services.

  • Website Designing
  • Website Development
  • Java Development
  • PHP Development
  • WordPress
  • Graphic Designing
  • Logo
  • Digital Marketing
  • On Page and Off Page SEO
  • PPC
  • Content Development
  • Corporate Training
  • Classroom and Online Training
  • Data Entry

Training For College Campus

JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected]
Duration: 1 week to 2 week

Источник

Понравилась статья? Поделить с друзьями:
  • Excel to jpg vba
  • Excel to jpg torrent
  • Excel to jpeg конвертация в онлайн
  • Excel to java table
  • Excel to html с картинками