How to create multi line cells in xlsx with openpyxl?
Question:
I have the following data:
test.json
file
{
"entries": [
{
"attributes": {
"sAMAccountName": "wonder-woman",
"memberOf": [
"woman",
"dc-comics",
"justice-league",
"human"
]
},
"dn": "CN=Diana Troy,OU=Users,OU=DC-COMICS,DC=universum,DC=local"
}
]
}
excl.json
file
{
"sAMAccountName": [
"ironman"
],
"dnsHostName": [
"dell"
]
}
I am trying to export it into an Excel file by code:
import json
from datetime import datetime
from openpyxl import Workbook
encoded_retrieved_users = './test.json'
accounts_excluded = './excl.json
with open(accounts_excluded, 'r', encoding="UTF-8") as file:
excluded_accounts = json.load(file)
excluded_users = excluded_accounts['sAMAccountName']
with open(encoded_retrieved_users, 'r', encoding="UTF-8") as file:
data = json.load(file)
retrieved_users = data['entries']
retrieved_users.sort(key=lambda d: d["attributes"]["sAMAccountName"])
def user_validation(suspect):
account = True
for account_checked in excluded_users:
if (account_checked == suspect):
account = False
return account
A = 'sAMAccountName'
B = 'memberOf'
# Set worksheet
wb = Workbook() # create excel worksheet
ws_01 = wb.active # Grab the active worksheet
ws_01.title = "all inf" # Set the title of the worksheet
# Set first row
row =1
ws_01.cell(row, 1, A) # cell(row, col, value)
ws_01.cell(row, 2, B)
# Set rest rows
row = 2
for user in retrieved_users:
attributes = user['attributes']
sAMAccountName = attributes['sAMAccountName']
if(user_validation(sAMAccountName) == True):
A = str(sAMAccountName)
ws_01.cell(row, 1, A)
for group_name in attributes['memberOf']:
B = group_name
ws_01.cell(row, 2, B)
# Save it in an Excel file
wb.save('./excel.xlsx)
However I would like that between each list-element a line break is entered, similar to ALT-ENTER in Excel. So at the end, the excel would look like this:
Answers:
You’re looking for wrap_text
parameter in openpyxl.styles.alignment
module.
import json
from openpyxl import Workbook
from openpyxl.styles import Alignment
# --- Reading .json files
with open("test.json") as json_enteries:
data1 = json.load(json_enteries)
with open("excl.json") as json_exclusions:
data2 = json.load(json_exclusions)
# --- Intersecting the two .json files
excluded_sAMAccountName, excluded_dnsHostName = set(data2.get("sAMAccountName",[])), set(data2.get("dnsHostName",[]))
items = [entry for entry in data1["entries"]
if entry["attributes"].get("sAMAccountName") not in excluded_sAMAccountName
or entry["attributes"].get("dnsHostName") not in excluded_dnsHostName]
# --- Creating the WB/WS
wb = Workbook()
ws = wb.active
ws.title = "all inf"
ws.append(["sAMAccountName", "memberOf"])
for idx, entry in enumerate(items, start=1):
ws.append([entry["attributes"]["sAMAccountName"], "n".join(entry["attributes"]["memberOf"])])
cell_value = ws.cell(row=idx+1,column=1).value
ws.cell(row=idx+1,column=2).alignment = Alignment(wrap_text=True)
ws.column_dimensions["B"].width = 15
ws.column_dimensions["A"].width = 20
wb.save("final.xlsx")
Output (Excel) :
I have the following data:
test.json
file
{
"entries": [
{
"attributes": {
"sAMAccountName": "wonder-woman",
"memberOf": [
"woman",
"dc-comics",
"justice-league",
"human"
]
},
"dn": "CN=Diana Troy,OU=Users,OU=DC-COMICS,DC=universum,DC=local"
}
]
}
excl.json
file
{
"sAMAccountName": [
"ironman"
],
"dnsHostName": [
"dell"
]
}
I am trying to export it into an Excel file by code:
import json
from datetime import datetime
from openpyxl import Workbook
encoded_retrieved_users = './test.json'
accounts_excluded = './excl.json
with open(accounts_excluded, 'r', encoding="UTF-8") as file:
excluded_accounts = json.load(file)
excluded_users = excluded_accounts['sAMAccountName']
with open(encoded_retrieved_users, 'r', encoding="UTF-8") as file:
data = json.load(file)
retrieved_users = data['entries']
retrieved_users.sort(key=lambda d: d["attributes"]["sAMAccountName"])
def user_validation(suspect):
account = True
for account_checked in excluded_users:
if (account_checked == suspect):
account = False
return account
A = 'sAMAccountName'
B = 'memberOf'
# Set worksheet
wb = Workbook() # create excel worksheet
ws_01 = wb.active # Grab the active worksheet
ws_01.title = "all inf" # Set the title of the worksheet
# Set first row
row =1
ws_01.cell(row, 1, A) # cell(row, col, value)
ws_01.cell(row, 2, B)
# Set rest rows
row = 2
for user in retrieved_users:
attributes = user['attributes']
sAMAccountName = attributes['sAMAccountName']
if(user_validation(sAMAccountName) == True):
A = str(sAMAccountName)
ws_01.cell(row, 1, A)
for group_name in attributes['memberOf']:
B = group_name
ws_01.cell(row, 2, B)
# Save it in an Excel file
wb.save('./excel.xlsx)
However I would like that between each list-element a line break is entered, similar to ALT-ENTER in Excel. So at the end, the excel would look like this:
You’re looking for wrap_text
parameter in openpyxl.styles.alignment
module.
import json
from openpyxl import Workbook
from openpyxl.styles import Alignment
# --- Reading .json files
with open("test.json") as json_enteries:
data1 = json.load(json_enteries)
with open("excl.json") as json_exclusions:
data2 = json.load(json_exclusions)
# --- Intersecting the two .json files
excluded_sAMAccountName, excluded_dnsHostName = set(data2.get("sAMAccountName",[])), set(data2.get("dnsHostName",[]))
items = [entry for entry in data1["entries"]
if entry["attributes"].get("sAMAccountName") not in excluded_sAMAccountName
or entry["attributes"].get("dnsHostName") not in excluded_dnsHostName]
# --- Creating the WB/WS
wb = Workbook()
ws = wb.active
ws.title = "all inf"
ws.append(["sAMAccountName", "memberOf"])
for idx, entry in enumerate(items, start=1):
ws.append([entry["attributes"]["sAMAccountName"], "n".join(entry["attributes"]["memberOf"])])
cell_value = ws.cell(row=idx+1,column=1).value
ws.cell(row=idx+1,column=2).alignment = Alignment(wrap_text=True)
ws.column_dimensions["B"].width = 15
ws.column_dimensions["A"].width = 20
wb.save("final.xlsx")
Output (Excel) :