使用 Python 将 Excel 转换为 JSON

新手上路,请多包涵

我有一个 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.')

提前致谢

原文由 NW_92 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1k
1 个回答

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

 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)

原文由 Vik 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题