【发布时间】: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.')
提前致谢
【问题讨论】:
-
发布的代码有什么具体问题?
-
这个之前的答案怎么样:stackoverflow.com/questions/53940031/…
-
Imo 你应该考虑使用 simplejson 包而不是试图重新发明轮子。
标签: python json excel python-3.x