How to format and write excel using pandas

2024/7/7 6:51:24

Lets assume that we have nested python dictionaries which should be written in single excel sheet file.

Following are sample dictionaries which can be used.

Car = [{"carbmodel": "Model A","attributes": {"make": "Brand X","year": 2023,"color": "Red","engine": "V6","transmission": "Automatic","features": ["GPS", "Bluetooth", "Leather Seats"]}},{"carbmodel": "Model B","attributes": {"make": "Brand Y","year": 2022,"color": "Blue","engine": "Inline-4","transmission": "Manual","features": ["Sunroof", "Backup Camera", "Alloy Wheels"]}},{"carbmodel": "Model C","attributes": {"make": "Brand Z","year": 2023,"color": "Black","engine": "V8","transmission": "Automatic","features": ["Apple CarPlay", "Heated Seats", "Navigation"]}}
]
bikes = [{"carbmodel": "Bike X","attributes": {"make": "Brand P","year": 2023,"color": "Green","engine": "250cc","transmission": "Manual","features": ["ABS", "LED Lights", "Digital Display"]}},{"carbmodel": "Bike Y","attributes": {"make": "Brand Q","year": 2022,"color": "Orange","engine": "200cc","transmission": "Manual","features": ["Disc Brakes", "Tubeless Tires", "Kick Start"]}},{"carbmodel": "Bike Z","attributes": {"make": "Brand R","year": 2023,"color": "Black","engine": "300cc","transmission": "Manual","features": ["Fuel Injection", "Mono Suspension", "Dual Exhaust"]}}
]

This should be written in excel file using pandas dataframe in following format which is shown in screenshot.enter image description here

Really appreciate any help, thank you in advance.

This is used code block for testing the scenario.

import xlsxwriter# Create a new Excel file
workbook = xlsxwriter.Workbook('merged_cells_and_data.xlsx')
worksheet = workbook.add_worksheet()# Add some content to the merged cells
cell_format = workbook.add_format({'bold': True,'align': 'center','valign': 'vcenter','bg_color': 'yellow'
})worksheet.merge_range('A1:E1', 'Merged Cells Example', cell_format)# Nested dictionary
useful_info = {'personal_info': {'name': 'John Doe','age': 30,'location': 'New York, USA'},'contact_info': {'email': '[email protected]','phone': '123-456-7890'},'employment': {'company': 'ABC Corporation','position': 'Software Engineer','years_experience': 5},'skills': ['Python', 'JavaScript', 'SQL', 'Problem Solving'],'education': {'university': 'University of XYZ','degree': 'Bachelor of Science in Computer Science','graduation_year': 2018}
}# Write nested dictionary starting from the 2nd row
row = 1
for key, value in useful_info.items():worksheet.write(row, 0, key)if isinstance(value, dict):for inner_key, inner_value in value.items():worksheet.write(row, 1, inner_key)worksheet.write(row, 2, inner_value)row += 1else:worksheet.write(row, 1, value)row += 1# Close the workbook
workbook.close()print("Excel file with merged cells and nested dictionary data created successfully.")
#Merge Cell issue with Multiple pandas #dataframe created from nested dictionaries 
mport xlsxwriterNested json added to dataframef1 = pd.DataFrame(sample_1).T 12= pd.DataFrame(sample_2).Trint(df1.shape[0])rint(df1.shape[1])ef multiple_dfs(df_list, sheets, file_name, spaces): writer = pd.ExcelWriter(file_name, engine='xlsxwriter') # Create an new Excel file and add a worksheet. workbook = xlsxwriter.Workbook("merge1.xlsx") worksheet = workbook.add_worksheet("Validation")# Increase the cell size of the merged cells to highlight the formatting.worksheet.set_column("A:E", 12)worksheet.set_row(3, 30)worksheet.set_row(6, 30)worksheet.set_row(7, 30)
# Create a format to use in the merged range. merge_format = workbook.add_format("bold": 1,"border": 1,"align":"center","valign": "vcenter","fg_color": "yellow".}# Merge 3 cells.worksheet.merge_range("A1:E1", "Merged Range", merge_format) # Create a format to use in the merged range.workbook.close()with pd.ExcelWriter(file_name) as writer:row = 3for dataframe in df_list:dataframe.to_excel (writer,sheet_name=sheets, startrow row, startcol=0)row row + len(dataframe.index) + spaces + 1#writer.close()#workbook.close()dfs = [df1, df2]## run functionmultiple_dfs(dfs, 'Validation', 'merge1.xlsx', 2)
Answer

The only missing part of your test code is converting list to string before writing to Excel.

# Write nested dictionary starting from the 2nd row
row = 1
for key, value in useful_info.items():worksheet.write(row, 0, key)if isinstance(value, dict):for inner_key, inner_value in value.items():worksheet.write(row, 1, inner_key)worksheet.write(row, 2, inner_value)row += 1else:if isinstance(value, list):value = ', '.join(value)worksheet.write(row, 1, value)row += 1

Writing data to Excel with Pandas is similar to using XlsxWriter. Here is a sample snippet:

import pandas as pd
df = pd.DataFrame({'Data': [1, 2, 3],'Total': [4, 5, 6]}) 
writer = pd.ExcelWriter(r'd:/temp/output.xlsx', engine='xlsxwriter') 
# Convert index to column if needed
df.reset_index().to_excel(writer, sheet_name='Sheet1', index=False)  
# Access the XlsxWriter workbook and sheet
workbook = writer.book
worksheet = writer.sheets['Sheet1']
# Add formatting - merge, font, border
style = {'bold': True, 'font_color': 'blue', 'font_size': 18, 'font_name': 'Arial' }
worksheet.merge_range('A1:B1', 'Report', workbook.add_format(style))
writer.close()
https://en.xdnf.cn/q/120370.html

Related Q&A

Openpyxl is unable to read after modifying

Requirement : 1.create a gui using Tkinter 2.Update the excel by fetching values from Tkinter entry widget 3.Read another sheet of the same workbook 4.plot graph using inside the Tkinter window.Prob…

Rounding datetime based on time of day

I have a pandas dataframe with timestamps shown below:6/30/2019 3:45:00 PMI would like to round the date based on time. Anything before 6AM will be counted as the day before. 6/30/2019 5:45:00 AM -&g…

Scraping Project Euler site with scrapy [closed]

Closed. This question needs debugging details. It is not currently accepting answers.Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to repro…

Python date function bugs

I am trying to create a function in python which will display the date. So I can see the program run, I have set one day to five seconds, so every five seconds it will become the next day and it will p…

Retreiving data from a website [duplicate]

This question already has answers here:How to determine the IP address of the server after connecting with urllib2?(4 answers)Closed 9 years ago.Im terribly sorry if this is unacceptable or answered e…

How to comma separate an array of integers in python? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.Want to improve this question? Add details and clarify the problem by editing this post.Closed 5 years ago.Improve…

Python 2.7.5 - Where is it installed on Windows Vista? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.This question does not appear to be about a specific programming problem, a software algorithm, or s…

Python list of lists specific path combinations or permutations

I have a list of lists and am looking for something similar to combinations or permutations, but there are conditions that may result in good "Path" or "Dead_End". If "Dead_En…

Python packages.import sys vs from sys import argv

Im trying to use argv into my python script. For this im using following code:from sys import argv script, file_name = argv print(file_name)python3 e.py e.txt This code works fine.But when I use:import…

How to reorganize a list of tuples?

Say I had a list of tuples:[(98, studentA), (97, studentB), (98, studentC), (95,studentD)]And I wanted to organize it so that the students are grouped together by the first number in the tuple, what wo…