Excel to json macro

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

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

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.

 

Добрый день, имеется выгрузка в excell в табличном виде, нужно данные сохранить в json структуре, через формулу «=» практически получил нужную структуру но не могу последнюю проблему решить как объяснить макросу, что если работа входит в фазу (суммарную работу), то нужно добавить в конце » ]} » и добавить столько в зависимости от уровня раз. (надеюсь последнее предложение более или менее понятно объяснил)).
в примере на вкладке «пример» есть исходные данные, и итоговый формат который получилось достичь через «=» , в M26,N26,O26 те самые формулы в зависимости от типа столбец L подставляется та или иная формула, но в примечании столбец P указал, что не получается сделать.
во вкладке json столбец A это то что получилось а в столбце C то что руками исправил, и что автоматом бы получить, (выделил жирным)
Может подскажете макрос или еще какой нибудь метод решения данной проблемы?

Прикрепленные файлы

  • Пример.xlsx (17.13 КБ)

 

Doober

Пользователь

Сообщений: 2201
Регистрация: 09.04.2013

Здравствуйте.опубликуйте результирующий json, на пару строк с таблицы.
Возможно помогу макросом.

 

Добрый день, вот пример файла на всю таблицу

Прикрепленные файлы

  • data.rar (307 Б)

 

Doober

Пользователь

Сообщений: 2201
Регистрация: 09.04.2013

В макросе изложен принцип формирования JSON.
Если у вас офис 64 битный, скину другой вариант, есть особенности.

Прикрепленные файлы

  • Пример.xlsm (61.11 КБ)

 

Добрый день, если я правильно понял, то в макросе test, Вы вручную всю структуру завели? тогда не очень понятен принцип формирования json структуры… или я не туда смотрю…может укажете куда смотреть?

 

Doober

Пользователь

Сообщений: 2201
Регистрация: 09.04.2013

Во вложении Ваш отформатированный json ,структуру  в макросе создал согласно файла руками.
В макросе показан принцип формирования.труда не должно составить для написания реального макроса.
children -это массив, остальное объект.

Прикрепленные файлы

  • data.zip (505 Б)

Изменено: Doober13.03.2017 12:04:48

 

Сергей Шистеров

Пользователь

Сообщений: 249
Регистрация: 01.01.1970

#7

16.03.2017 07:12:23

 я увидел что формируется, но проблема в другом получается если у меня будет 300 строк мне всю структуру необходимо будет в макрос писать? и так под каждую новую структуру?
нашел макрос

Код
Public Sub exceltojson()
Dim rng As Range, items As New Collection, myitem As New Dictionary, i As Integer, cell As Variant
set rng = Range("A2:A3")
'Set rng = Range(Sheets(2).Range("A2"), Sheets(2).Range("A2").End(xlDown)) use this for dynamic range
i = 0
For Each cell In rng
Debug.Print (cell.Value)
myitem("name") = cell.Value
myitem("email") = cell.Offset(0, 1).Value
myitem("phone") = cell.Offset(0, 2).Value
items.Add myitem
Set myitem = Nothing
i = i + 1
Next
Sheets(1).Range("A4").Value = ConvertToJson(items, Whitespace:=2)
End Sub

ниже библиотека для подключения JsonConverter.zip (8.01 КБ)
но выходит ошибка на myitem As New Dictionary
, в принципе макрос годный но как children структуру создавать проблема.

Изменено: Сергей Шистеров16.03.2017 07:16:02

 

Максим Зеленский

Пользователь

Сообщений: 4646
Регистрация: 11.06.2014

Microsoft MVP

#8

16.03.2017 12:36:17

Сергей Шистеров, спасибо за наводку, интересная библиотека, надо ее поковырять, уж очень она навернутая.
По

Цитата
Сергей Шистеров написал:
на myitem As New Dictionary

https://github.com/VBA-tools/VBA-JSON#installation

добавьте в редакторе VBA референс на «Microsoft Scripting Runtime»

Но в вашем случае проблема не в конвертации строки в json, а в объяснении любому конвертеру, что в этом месте заканчивается объект или массив (или несколько объектов/массивов). Начинал возиться да потом отвлекли, бросил.

F1 творит чудеса

 

Вот полностью рабочий вариант , этой библиотеки с примерами, но Children так мне и не победить(

https://cloud.mail.ru/public/KBCQ/24FFyvYFh

размер 150 кб не влазит на форум даже в архиве

Изменено: Сергей Шистеров16.03.2017 13:02:03

 

Сергей Шистеров

Пользователь

Сообщений: 249
Регистрация: 01.01.1970

#10

16.03.2017 12:57:44

вот другой пример, где добавляется Location мне бы вместо него, типа проверки если фаза то children :[

Код
Public Sub exceltonestedjson()
Dim rng As Range, items As New Collection, myitem As New Dictionary, subitem As New Dictionary, i As Integer, cell As Variant
Set rng = Range("A2:A3")
'Set rng = Range(Sheets(2).Range("A2"), Sheets(2).Range("A2").End(xlDown)) use this for dynamic range
i = 0
For Each cell In rng
Debug.Print (cell.Value)
myitem("name") = cell.Value
myitem("email") = cell.Offset(0, 1).Value
myitem("phone") = cell.Offset(0, 2).Value
subitem("country") = cell.Offset(0, 3).Value
myitem.Add "location", subitem
items.Add myitem
Set myitem = Nothing
Set subitem = Nothing
i = i + 1
Next
Sheets(2).Range("A4").Value = ConvertToJson(items, Whitespace:=2)
End Sub

Изменено: Сергей Шистеров16.03.2017 13:01:03

 

Сергей Шистеров

Пользователь

Сообщений: 249
Регистрация: 01.01.1970

#11

17.03.2017 11:52:41

Код
Sub customJSON_3()
Dim mainContainer As New Collection, tempContainer As New Dictionary, children As New Collection
tempContainer.Add "name", Range("B3").Value
tempContainer.Add "dateStart", Range("C3").Value
children.Add tempContainer
Set tempContainer = Nothing
tempContainer.Add "name", Range("B2").Value
tempContainer.Add "dateStart", Range("C2").Value
tempContainer.Add "children", children
mainContainer.Add tempContainer
Sheets(1).Range("H10").Value = ConvertToJson(mainContainer, Whitespace = 2)
End Sub

результат его работы

Код
[
{
"name": "Work",
"dateStart": "2017-05-04",
"children": [
{
"name": "Next",
"dateStart": "2017-05-04"
}
]
}
]

Подскажите как его адаптировать под мою задачу?
чтобы либо по WBS структуру создавал либо если в ячейке указано «НЕТ» то все что ниже, до следующего «НЕТ» заводил под children

 

Не стал пока колбаситься с макросом, сделал формулами.
Разбил на три части для облегчения понимания:
1. Фикс.часть
2. Завершение «Фаза или Работа»
3. Закрытие объекта или списка

Проверьте

 

Сергей Шистеров

Пользователь

Сообщений: 249
Регистрация: 01.01.1970

#13

21.03.2017 09:52:38

Да спасибо, все работает!

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

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