Python Excel 到 JSON 的转换

在本教程中,我们将研究两种 Python 模块来将 excel 文件转换为 JSON。

  1. excel2json-3
  2. (/社区/教程/python-pandas-模块-教程)

使用 excel2json-3 模块将 Excel 文件转换为 JSON 文件

这是一个非常简单的模块,将excel文件转换为JSON文件。从excel文件的内容被转换为JSON字符串并保存到一个文件中。文件的名称是由excel文件的名称衍生出来的。所以,如果有两个名为NumbersCars的文件,那么JSON文件将分别被命名为Numbers.json和Cars.json。该模块支持.xls 和.xlsx 文件格式进行转换。我们可以从文件系统以及URL读取excel文件。我们可以使用PIP命令安装这个模块。

1$ pip install excel2json-3

For our example, I have created an excel file named "records.xlsx" having three sheets. Python Excel File To Json Example Here is the script to convert this excel file to JSON files.

1import excel2json
2
3excel2json.convert_from_file('records.xlsx')

此脚本会创建三个 JSON 文件。 Employees.json

 1[
 2    {
 3        "EmpID": 1.0,
 4        "EmpName": "Pankaj",
 5        "EmpRole": "CEO"
 6    },
 7    {
 8        "EmpID": 2.0,
 9        "EmpName": "David Lee",
10        "EmpRole": "Editor"
11    },
12    {
13        "EmpID": 3.0,
14        "EmpName": "Lisa Ray",
15        "EmpRole": "Author"
16    }
17]

卡斯.琼斯

 1[
 2    {
 3        "Car Name": "Honda City",
 4        "Car Model": "City",
 5        "Car Maker": "Honda",
 6        "Car Price": "20,000 USD"
 7    },
 8    {
 9        "Car Name": "Bugatti Chiron",
10        "Car Model": "Chiron",
11        "Car Maker": "Bugatti",
12        "Car Price": "3 Million USD"
13    },
14    {
15        "Car Name": "Ferrari 458",
16        "Car Model": 458.0,
17        "Car Maker": "Ferrari",
18        "Car Price": "2,30,000 USD"
19    }
20]

數字:JSON

 1[
 2    {
 3        "1.0": 3.0,
 4        "2.0": 4.0
 5    },
 6    {
 7        "1.0": "N1",
 8        "2.0": "N2"
 9    },
10    {
11        "1.0": 5.0,
12        "2.0": 6.0
13    },
14    {
15        "1.0": 7.0,
16        "2.0": 8.0
17    }
18]

如果您需要从 URL 读取 Excel 文件,请使用 convert_from_url() 函数。

excel2json-3 模块的限制

  • 插件具有非常有限的功能
  • 没有任何选项可以跳过任何表、行和列,这使得它很难使用较大的Excel文件
  • JSON被保存成文件。

使用 Pandas 模块将 Excel 表格转换为 JSON String

Pandas 模块提供了读取 excel 表格到 DataFrame 对象的功能. 有许多选项来指定标题,读取特定列,跳过行等你可以阅读更多关于它在 Pandas read_excel() – Reading Excel File in Python.我们可以使用 to_json() 函数将 DataFrame 对象转换为 JSON 字符串。

1import pandas
2
3excel_data_df = pandas.read_excel('records.xlsx', sheet_name='Employees')
4
5json_str = excel_data_df.to_json()
6
7print('Excel Sheet to JSON:\n', json_str)

输出:

1Excel Sheet to JSON:
2 {"EmpID":{"0":1,"1":2,"2":3},"EmpName":{"0":"Pankaj","1":"David Lee","2":"Lisa Ray"},"EmpRole":{"0":"CEO","1":"Editor","2":"Author"}}

因此, JSON 数据是用列方向创建的. 如果您想创建 JSON 字符串以行方向方向,请将方向参数值传递为记录

1json_str = excel_data_df.to_json(orient='records')

输出:

1Excel Sheet to JSON:
2 [{"EmpID":1,"EmpName":"Pankaj","EmpRole":"CEO"},{"EmpID":2,"EmpName":"David Lee","EmpRole":"Editor"},{"EmpID":3,"EmpName":"Lisa Ray","EmpRole":"Author"}]

结论

如果你有一个简单而结构齐全的Excel文件,你想将其转换为JSON文件,请使用excel2json-3模块,但如果你想对Excel数据的读取和转换为JSON字符串的方式有更多的控制权,请使用panda的模块。

参考

Published At
Categories with 技术
Tagged with
comments powered by Disqus