【发布时间】:2023-01-18 18:31:43
【问题描述】:
我有一个 json 文件,其中包含我想保存到 xlsx 文件中的数据。我使用了 openpyxl 库,并在创建 for 循环的阶段停止,将每个用户依次保存在单独的行中,并将他的数据保存在单独的单元格中。
json 文件:
{
"entries": [
{
"attributes": {
"cn": "Bruce Wayne",
"displayName": "Batman",
"distinguishedName": "CN=Bruce Wayne,OU=Users,OU=DC-COMICS,DC=universum,DC=local",
"primaryGroupID": 513,
"sAMAccountName": "batman",
"sAMAccountType": 805306368,
"userAccountControl": 514,
"whenCreated": "2016-04-19 10:06:25+00:00"
},
"dn": "CN=Bruce Wayne,OU=Users,OU=DC-COMICS,DC=universum,DC=local"
},
{
"attributes": {
"cn": "Clark Kent",
"displayName": "Superman",
"distinguishedName": "CN=Clark Kent,OU=Users,OU=DC-COMICS,DC=universum,DC=local",
"primaryGroupID": 513,
"sAMAccountName": "superman",
"sAMAccountType": 805306368,
"userAccountControl": 514,
"whenCreated": "2016-04-19 10:06:25+00:00"
},
"dn": "CN=Clark Kent,OU=Users,OU=DC-COMICS,DC=universum,DC=local"
}
]
}
我的代码:
import json
import configparser
### load main_config.ini file
main_config_file = './config/main_config.ini' # sciezka do pliku main_config.ini z
ustawieniami
main_config = configparser.RawConfigParser()
main_config.read(main_config_file)
### VARIABLES
# from configs files
root_path = main_config['GLOBAL']['root_path']
json_dir = main_config['GLOBAL']['json_dir']
encoded_retrived_users_file = main_config['USERS']['encoded_users_file_name']
# load data from JSON file
encoded_retrived_users = './JSON/test.json'
#encoded_retrived_users = root_path + json_dir + encoded_retrived_users_file # sciezka
do pliku encoded_users_from_LDAP.json
with open(encoded_retrived_users, 'r', encoding="UTF-8") as file:
data = json.load(file)
retrived_users = data['entries']
### CONSOLE VIEW
print("----------------------------------")
for user in retrived_users:
no = str(i)
attributes = user['attributes']
cn = attributes['cn']
sAMAccountName = attributes['sAMAccountName']
i += i
print("No: " + no)
print("cn: " + cn)
print("sAMAccountName: " + sAMAccountName)
print("----------------------------------")
### EXCEL
import openpyxl
from openpyxl import Workbook
wb = Workbook()
# Grab the active worksheet
ws_01 = wb.active
# Set the title of the worksheet
ws_01.title = "llogon>30d"
# Set first row
ws_01.cell(1, 1, "cn")
ws_01.cell(1, 2, "sAMA")
# Save it in an Excel file
wb.save("./test/test.xlsx")
我想要的是:
【问题讨论】:
-
使用熊猫是一种选择吗?
-
问题中没有写入 Excel 的代码。在调用
import openpyxl时,retrived_users是一个对象数组,而不是 JSON。您是否尝试过遍历retrived_users并将您想要的属性写入 Excel?例如ws_01.cell(iRow, 1, attributes["cn"])
标签: python python-3.x openpyxl