我有這樣的 Excel 檔案:
-------------------------
| myValue | myValue2 | myValue3 |
-------- ------- --------
| 1 | A | AA|
| 2 | B | BB|
| 4 | C | CC |
| 5 | D | DD |
| 6 | E | EE|
| 7 | F | FF |
| 8 | G | GG |
--------------------------
我想將我的 Excel 檔案轉換為 JSON 之類的
{
"myValue":
{
"1":"1",
"2":"2"
},
"myValue2":
{
"A":"A",
"B":"B"
},
"myValue3":
{
"AA":"AA",
"BB":"BB"
}
}
我已經有一個這樣的 JSON 檔案,所以我應該將 Excel 中的值附加到該檔案中。它應該將“myValue”下的值添加到該檔案中“myValue”下的另一個 JSON 檔案中。我已經從網站上嘗試了一些解決方案,但它們對我不起作用。此外,問題在于myValue、myValue2、myValue3 并不總是與此處顯示的順序相同。理想的解決方案是在已經包含它的 JSON 檔案中找到 myValue 并直接從包含相同值的 Excel 行添加值。
uj5u.com熱心網友回復:
這有效
# Importing dependencies
import pandas
import json
# Reading xlsx into pandas dataframe
df = pandas.read_excel('../Data/18-12-21.xlsx')
# Encoding/decoding a Dataframe using 'columns' formatted JSON
jsonfile = df.to_json(orient='columns')
# Print out the result
print('Excel Sheet to JSON:\n', jsonfile)
# Make the string into a list to be able to input in to a JSON-file
json_dict = json.loads(jsonfile)
# write from and file to write to
with open('data.json', 'w') as json_file:
json.dump(json_dict, json_file)
輸出
{
"myValue": {
"0": 1,
"1": 2,
"2": 4,
"3": 5,
"4": 6,
"5": 7,
"6": 8
},
"myValue2": {
"0": "A",
"1": "B",
"2": "C",
"3": "D",
"4": "E",
"5": "F",
"6": "G"
},
"myValue3": {
"0": "AA",
"1": "BB",
"2": "CC",
"3": "DD",
"4": "EE",
"5": "FF",
"6": "GG"
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/385793.html
