我有一个 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 许可协议
经历了几个解决方案,这是最适合我的解决方案。希望这可以节省别人一些时间。