簡體   English   中英

通過python openpyxl將JSON文件中的數據寫入Excel

[英]Write data from JSON file to Excel by python openpyxl

我有一個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")

我想要的是:

在此處輸入圖像描述

在調用import openpyxl時, retrived_users是一個對象數組,而不是 JSON。寫入控制台的相同代碼可用於寫入 Excel 文件:

wb = Workbook()
ws_01 = wb.active
ws_01.title = "llogon>30d"

i=0
for user in retrived_users:
    no = str(i)
    attributes = user['attributes']
    cn = attributes['cn']
    sAMAccountName = attributes['sAMAccountName']

    ws_01.cell(i, 1, cn)
    ws_01.cell(i, 2, sAMAccountName)
    i += i
wb.save("./test/test.xlsx")

編寫更優雅的代碼當然是可能的,但這應該可行

使用的選項:

import pandas as pd
import json

with open('test.json') as f:
    j = json.load(f)

df = pd.DataFrame({
    k:[i['attributes'][k] for i in j['entries']]
    for k in j['entries'][0]['attributes'].keys()
})
df.whenCreated = pd.to_datetime(df.whenCreated).dt.tz_localize(None)
df.to_excel('test.xlsx')
Output:

創建的 Excel 工作表的屏幕截圖

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM