【问题标题】:Converting Excel into JSON using Python使用 Python 将 Excel 转换为 JSON
【发布时间】:2020-02-03 17:24:52
【问题描述】:

我有一个 excel 文件,我想将其转换为 JSON 文件。所以excel是这样的:

-------------------------
| Col A | Col C | Col F |
--------+-------+--------
|   1   |   A   |   EE  |
|   2   |   B   |   FF  |
|   4   |   C   |   FF  |
|   5   |   D   |   HH  |
|   6   |   D   |   HH  |
|   7   |   A   |   EE  |
|   8   |   E   |   EE  |
--------------------------

我希望JSON 遵循这种格式:

{
"EE": {
    "A": {
      "Col A key": "1",
      "Col A key": "7"
    },
    "E": {
      "Col A key": "8"
    },
  },

"FF": {
    "B": {
      "Col A key": "2"
    },
    "C": {
      "Col A key": "4"
    }
  },

"HH": {
    "D": {
      "Col A key": "5",
      "Col A key": "6"
    }
  }

}

谁能帮我用python 实现这个?我尝试了各种方法,但没有成功。这是我到目前为止所做的:


import openpyxl, pprint, json
print('Opening workbook...')
wb = openpyxl.load_workbook('excel_form.xlsx')
sheet = wb.get_sheet_by_name('Sheet')


excel_data = {}
print('Reading rows...')
for row in range(2, sheet.max_row + 1):
    Col F  = sheet['F' + str(row)].value
    Col C = sheet['C' + str(row)].value
    Col A = sheet['A' + str(row)].value

    excel_data.setdefault(Col F, {})
    excel_data[Col F].setdefault(Col C, {'Col A': Col A})


# Open a new text file and write the contents of excel_data to it.
print('Writing results...')
with open('DATA.json', 'w') as resultFile:
    json.dump(Matrix, resultFile)
print('Done.')

提前致谢

【问题讨论】:

标签: python json excel python-3.x


【解决方案1】:

我更喜欢使用 xlrd 将 Excel 行转换为 JSON 格式。

import xlrd
from collections import OrderedDict
import json

打开工作簿并选择第一个工作表

wb = xlrd.open_workbook("Excel-sheet location here")
sh = wb.sheet_by_index(0)

创建一个列表来保存字典

data_list = []

遍历工作表中的每一行并将值提取到字典中

for rownum in range(1, sh.nrows):
     data = OrderedDict()

row_values = sh.row_values(rownum)
data['<Column Name1>'] = row_values[0]
data['<Column Name2>'] = row_values[1]
data_list.append(data)

写入文件:

 with open("RulesJson.json", "w", encoding="utf-8") as writeJsonfile:
      json.dump(data_list, writeJsonfile, indent=4,default=str) 

【讨论】:

    【解决方案2】:

    经历了几个解决方案,这是最适合我的一个。希望这可以为其他人节省一些时间。

    import pandas
    import json
    
    # Read excel document
    excel_data_df = pandas.read_excel('data.xlsx', sheet_name='sheet1')
    
    # Convert excel to string 
    # (define orientation of document in this case from up to down)
    thisisjson = excel_data_df.to_json(orient='records')
    
    # Print out the result
    print('Excel Sheet to JSON:\n', thisisjson)
    
    # Make the string into a list to be able to input in to a JSON-file
    thisisjson_dict = json.loads(thisisjson)
    
    # Define file to write to and 'w' for write option -> json.dump() 
    # defining the list to write from and file to write to
    with open('data.json', 'w') as json_file:
        json.dump(thisisjson_dict, json_file)
    

    【讨论】:

    • NameError: name 'json' is not defined
    【解决方案3】:

    2 种方法 可实现该结果:

    1. 使用excel2json。这是一个非常简单的工具,但可能对您有所帮助。
      • 首先,使用pip 安装包excel2json-3
      • 然后,运行此代码块应该为文件中的每个工作表输出一个JSON 文件:
    import excel2json
    
    excel2json.convert_from_file('excel_form.xlsx')
    

    1. 使用pandas。如果您正在寻找更全面的解决方案,您不妨发现pandas 很有用。它是一个为数据操作而设计的库,并具有更多功能。
      • 首先通过pip 安装pandas
      • 然后,运行此代码应该会打印一个 JSON 字符串,描述名为 Sheet 的 Excel 工作表。
    import pandas
    
    excel_data_fragment = pandas.read_excel('excel_form.xlsx', sheet_name='Sheet')
    
    json_str = excel_data_fragment.to_json()
    
    print('Excel Sheet to JSON:\n', json_str)
    

    Link to the source

    【讨论】:

    • 出现 AttributeError: module 'excel2json' has no attribute 'convert_from_file' 错误
    • pandas 如果您只是想读入数据,这有点矫枉过正。如果您想以某种利用pandas 的方式转换数据,那会更理想。
    【解决方案4】:

    您可以查看此工具,也许会有所帮助:

    Flatten 工具是一个 Python 库和命令行界面,用于将单页或多页电子表格转换为 JSON 文档并再次转换回来。

    https://flatten-tool.readthedocs.io/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-09
      • 2015-04-19
      • 1970-01-01
      • 2021-12-06
      • 1970-01-01
      • 2018-07-17
      • 1970-01-01
      • 2023-02-14
      相关资源
      最近更新 更多