The xlsxwriter
library is great for creating .xlsx
files (originally mentioned by Fatih1923).
The following snippet generates an .xlsx
file from a list of dicts while stating the order and the displayed names:
import xlsxwriter
# ...
def create_xlsx_file(file_path: str, headers: dict, items: list):
with xlsxwriter.Workbook(file_path) as workbook:
worksheet = workbook.add_worksheet()
worksheet.write_row(row=0, col=0, data=headers.values())
header_keys = list(headers.keys())
for index, item in enumerate(items):
row = map(lambda field_id: item.get(field_id, ''), header_keys)
worksheet.write_row(row=index + 1, col=0, data=row)
Usage
headers = {
'bank': 'Money in Bank',
'dailyWinners': 'Daily Winners',
'dailyFree': 'Daily Free',
'user': 'User',
}
players = [
{'dailyWinners': 3, 'dailyFreePlayed': 2, 'user': 'Player1', 'bank': 0.06},
{'dailyWinners': 3, 'dailyFreePlayed': 2, 'user': 'Player2', 'bank': 4.0},
{'dailyWinners': 1, 'dailyFree': 2, 'user': 'Player3', 'bank': 3.1},
{'dailyWinners': 3, 'dailyFree': 2, 'user': 'Player4', 'bank': 0.32}
]
create_xlsx_file("my xslx file.xlsx", headers, players)
💡 Note — The
headers
dict represent both the order and the displayed name. If you’re not using Python3.6+, useOrderedDict
inheaders
, since the order indict
is not preserved
In this article, you will see everything about how to convert Dictionary to Excel in Python with the help of examples. Most of the time you will need to convert Python dictionaries or a list of Python dictionaries into excel. Then this article is going to be very helpful for you.
Prerequisites
Before going further into this article you will need to install the following packages using the pip command, If you have already installed then you can ignore them.
pip install pandas
pip install openpyxl
Headings of Contents
- 1 How to convert Dictionary to excel in Python
- 1.1 Convert Dictionary to Excel in Python
- 1.2 Convert List of Dictionary to Excel in Python
- 2 Conclusion
How to convert Dictionary to excel in Python
Here we will see a total of two ways to convert Python dictionaries into excel. The first is converting a single dictionary to excel and the second will be converting a list of dictionaries into excel.
Convert Dictionary to Excel in Python
Here I’m gonna convert only a single Python Dictionary to an excel file using the Python Pandas library.
In this example, we will see how to convert the Python dictionary to excel using the Python pandas module.
Example: Convert a dictionary to excel
import pandas as pd
student = {"Name": "Vishvajit Rao", "age": 23, "Occupation": "Developer","Language": "Python"}
# convert into dataframe
df = pd.DataFrame(data=student, index=[1])
#convert into excel
df.to_excel("students.xlsx", index=False)
print("Dictionary converted into excel...")
After the above code is executed successfully, students.xlsx will create.
Convert List of Dictionary to Excel in Python
Sometimes you may want to convert the list of Python dictionaries to an Excel file. then again, you can follow the below approach.
Most of the time you have a large list of dictionaries and you want to convert them into excel, then it is also possible, Let’s see how can you do that.
Example: Convert a list of dictionaries to excel
import pandas as pd
student = [{"Name": "Vishvajit Rao", "age": 23, "Occupation": "Developer","Skills": "Python"},
{"Name": "John", "age": 33, "Occupation": "Front End Developer","Skills": "Angular"},
{"Name": "Harshita", "age": 21, "Occupation": "Tester","Skills": "Selenium"},
{"Name": "Mohak", "age": 30, "Occupation": "Full Stack","Skills": "Python, React and MySQL"}]
# convert into dataframe
df = pd.DataFrame(data=student)
#convert into excel
df.to_excel("students.xlsx", index=False)
print("Dictionary converted into excel...")
Output
Conclusion
So we have seen all about how to convert a dictionary to excel in Python with the help of examples. This is one of the most important especially when you are generating reports from large dictionaries into an excel file because dictionaries are not understandable by non-techie guys so you have an option to convert it into an excel file.
I hope this article will help you. if you like this article, please share and keep visiting for further interesting articles.
Related Articles:-
- How to convert a dictionary to CSV
- How to convert Excel to Dictionary in Python
- How to convert string to DateTime in Python
- How to sort the list of Dictionaries in Python
- How to convert Tuple to List In Python
Thanks for your valuable time… 🙏🙏
About the Author: Admin
Programming Funda aims to provide the best programming tutorials to all programmers. All tutorials are designed for beginners as well as professionals.
Programming Funda explains any programming article well with easy examples so that you programmer can easily understand what is really going on here.
View all post by Admin | Website
From the documentation, you can see that a worksheet object has an .append
method that let you write a row from an iterable at the bottom of said sheet. Documentation from the builtin help
is reproduced here:
Help on method append in module openpyxl.worksheet.worksheet:
append(iterable) method of openpyxl.worksheet.worksheet.Worksheet instance
Appends a group of values at the bottom of the current sheet.
* If it's a list: all values are added in order, starting from the first column
* If it's a dict: values are assigned to the columns indicated by the keys (numbers or letters)
:param iterable: list, range or generator, or dict containing values to append
:type iterable: list|tuple|range|generator or dict
Usage:
* append(['This is A1', 'This is B1', 'This is C1'])
* **or** append({'A' : 'This is A1', 'C' : 'This is C1'})
* **or** append({1 : 'This is A1', 3 : 'This is C1'})
:raise: TypeError when iterable is neither a list/tuple nor a dict
This means that your can sheet.append(headers)
instead of your ugly loop. Similarly, using .values()
on your dictionnaries, you can simplify your write_xls
function to:
def write_xls(filepath, dictionary):
wb = load_workbook(filepath)
sheet = wb.active
headers = list(dictionary[0])
sheet.append(headers)
for x in dictionary:
sheet.append(list(x.values()))
wb.save(filepath)
Now, a few more things to consider.
First off, since you are only interested in creating the file and writing in it, you may be interested in the write-only mode provided by openpyxl
. This mean you will simplify your code to a single function:
def write_xls(filepath, dictionary):
wb = Workbook(write_only=True)
sheet = wb.create_sheet()
headers = list(dictionary[0])
sheet.append(headers)
for x in dictionary:
sheet.append(list(x.values()))
wb.save(filepath)
Second, you relly very much on your data being presented well ordered and without flaws. This might bite you at some point. I would:
- find all possible headers in your dictionnaries and order them;
- use them to recreate each row using the same ordering each time.
This will allow you to have a coherent output, even with inputs such as:
things = [
{
"Fruit": "Orange",
"Flavour": "Good",
"Expiration": "21May20",
},
{
"Flavour": "Good",
"Fruit": "Apple",
"Expiration": "19May20",
},
{
"Flavour": "Regular",
"Expiration": "16May20",
"Fruit": "Banana",
}
]
or even:
things = [
{
"Fruit": "Orange",
"Flavour": "Good",
"Expiration": "21May20"
},
{
"Fruit": "Apple",
"Flavour": "Good",
"Junk": "Spam",
"Expiration": "19May20"
},
{
"Fruit": "Banana",
"Flavour": "Regular",
"Expiration": "16May20"
}
]
Proposed improvements:
import itertools
from openpyxl import Workbook
def write_xls(filename, data):
wb = Workbook(write_only=True)
ws = wb.create_sheet()
headers = list(set(itertools.chain.from_iterable(data)))
ws.append(headers)
for elements in data:
ws.append([elements.get(h) for h in headers])
wb.save(filename)
The following sections explain how to write various types of data to an Excel
worksheet using XlsxWriter.
Writing data to a worksheet cell
The worksheet
write()
method is the most common means of writing
Python data to cells based on its type:
import xlsxwriter workbook = xlsxwriter.Workbook('write_data.xlsx') worksheet = workbook.add_worksheet() worksheet.write(0, 0, 1234) # Writes an int worksheet.write(1, 0, 1234.56) # Writes a float worksheet.write(2, 0, 'Hello') # Writes a string worksheet.write(3, 0, None) # Writes None worksheet.write(4, 0, True) # Writes a bool workbook.close()
The write()
method uses the type()
of the data to determine which
specific method to use for writing the data. These methods then map some basic
Python types to corresponding Excel types. The mapping is as follows:
Python type | Excel type | Worksheet methods |
---|---|---|
int |
Number | write() , write_number() |
long |
||
float |
||
Decimal |
||
Fraction |
||
basestring |
String | write() , write_string() |
str |
||
unicode |
||
None |
String (blank) | write() , write_blank() |
datetime.date |
Number | write() , write_datetime() |
datetime.datetime |
||
datetime.time |
||
datetime.timedelta |
||
bool |
Boolean | write() , write_boolean() |
The write()
method also handles a few other Excel types that are
encoded as Python strings in XlsxWriter:
Pseudo-type | Excel type | Worksheet methods |
---|---|---|
formula string | Formula | write() , write_formula() |
url string | URL | write() , write_url() |
It should be noted that Excel has a very limited set of types to map to. The
Python types that the write()
method can handle can be extended as
explained in the Writing user defined types section below.
Writing lists of data
Writing compound data types such as lists with XlsxWriter is done the same way
it would be in any other Python program: with a loop. The Python
enumerate()
function is also very useful in this context:
import xlsxwriter workbook = xlsxwriter.Workbook('write_list.xlsx') worksheet = workbook.add_worksheet() my_list = [1, 2, 3, 4, 5] for row_num, data in enumerate(my_list): worksheet.write(row_num, 0, data) workbook.close()
Or if you wanted to write this horizontally as a row:
import xlsxwriter workbook = xlsxwriter.Workbook('write_list.xlsx') worksheet = workbook.add_worksheet() my_list = [1, 2, 3, 4, 5] for col_num, data in enumerate(my_list): worksheet.write(0, col_num, data) workbook.close()
For a list of lists structure you would use two loop levels:
import xlsxwriter workbook = xlsxwriter.Workbook('write_list.xlsx') worksheet = workbook.add_worksheet() my_list = [[1, 1, 1, 1, 1], [2, 2, 2, 2, 1], [3, 3, 3, 3, 1], [4, 4, 4, 4, 1], [5, 5, 5, 5, 1]] for row_num, row_data in enumerate(my_list): for col_num, col_data in enumerate(row_data): worksheet.write(row_num, col_num, col_data) workbook.close()
The worksheet class has two utility functions called
write_row()
and write_column()
which are basically a loop around
the write()
method:
import xlsxwriter workbook = xlsxwriter.Workbook('write_list.xlsx') worksheet = workbook.add_worksheet() my_list = [1, 2, 3, 4, 5] worksheet.write_row(0, 1, my_list) worksheet.write_column(1, 0, my_list) workbook.close()
Writing dicts of data
Unlike lists there is no single simple way to write a Python dictionary to an
Excel worksheet using Xlsxwriter. The method will depend of the structure of
the data in the dictionary. Here is a simple example for a simple data
structure:
import xlsxwriter workbook = xlsxwriter.Workbook('write_dict.xlsx') worksheet = workbook.add_worksheet() my_dict = {'Bob': [10, 11, 12], 'Ann': [20, 21, 22], 'May': [30, 31, 32]} col_num = 0 for key, value in my_dict.items(): worksheet.write(0, col_num, key) worksheet.write_column(1, col_num, value) col_num += 1 workbook.close()
Writing dataframes
The best way to deal with dataframes or complex data structure is to use
Python Pandas. Pandas is a Python data analysis
library. It can read, filter and re-arrange small and large data sets and
output them in a range of formats including Excel.
To use XlsxWriter with Pandas you specify it as the Excel writer engine:
import pandas as pd # Create a Pandas dataframe from the data. df = pd.DataFrame({'Data': [10, 20, 30, 20, 15, 30, 45]}) # Create a Pandas Excel writer using XlsxWriter as the engine. writer = pd.ExcelWriter('pandas_simple.xlsx', engine='xlsxwriter') # Convert the dataframe to an XlsxWriter Excel object. df.to_excel(writer, sheet_name='Sheet1') # Close the Pandas Excel writer and output the Excel file. writer.close()
The output from this would look like the following:
For more information on using Pandas with XlsxWriter see Working with Pandas and XlsxWriter.
Writing user defined types
As shown in the first section above, the worksheet write()
method
maps the main Python data types to Excel’s data types. If you want to write an
unsupported type then you can either avoid write()
and map the user type
in your code to one of the more specific write methods or you can extend it
using the add_write_handler()
method. This can be, occasionally, more
convenient then adding a lot of if/else logic to your code.
As an example, say you wanted to modify write()
to automatically write
uuid
types as strings. You would start by creating a function that
takes the uuid, converts it to a string and then writes it using
write_string()
:
def write_uuid(worksheet, row, col, uuid, format=None): return worksheet.write_string(row, col, str(uuid), format)
You could then add a handler that matches the uuid
type and calls your
user defined function:
# match, action() worksheet.add_write_handler(uuid.UUID, write_uuid)
Then you can use write()
without further modification:
my_uuid = uuid.uuid3(uuid.NAMESPACE_DNS, 'python.org') # Write the UUID. This would raise a TypeError without the handler. worksheet.write('A1', my_uuid)
Multiple callback functions can be added using add_write_handler()
but
only one callback action is allowed per type. However, it is valid to use the
same callback function for different types:
worksheet.add_write_handler(int, test_number_range) worksheet.add_write_handler(float, test_number_range)
How the write handler feature works
The write()
method is mainly a large if()
statement that checks the
type()
of the input value and calls the appropriate worksheet method to
write the data. The add_write_handler()
method works by injecting
additional type checks and associated actions into this if()
statement.
Here is a simplified version of the write()
method:
def write(self, row, col, *args): # The first arg should be the token for all write calls. token = args[0] # Get the token type. token_type = type(token) # Check for any user defined type handlers with callback functions. if token_type in self.write_handlers: write_handler = self.write_handlers[token_type] function_return = write_handler(self, row, col, *args) # If the return value is None then the callback has returned # control to this function and we should continue as # normal. Otherwise we return the value to the caller and exit. if function_return is None: pass else: return function_return # Check for standard Python types, if we haven't returned already. if token_type is bool: return self.write_boolean(row, col, *args) # Etc. ...
The syntax of write handler functions
Functions used in the add_write_handler()
method should have the
following method signature/parameters:
def my_function(worksheet, row, col, token, format=None): return worksheet.write_string(row, col, token, format)
The function will be passed a worksheet instance, an
integer row
and col
value, a token
that matches the type added to
add_write_handler()
and some additional parameters. Usually the
additional parameter(s) will only be a cell format
instance. However, if you need to handle other additional parameters, such as
those passed to write_url()
then you can have more generic handling
like this:
def my_function(worksheet, row, col, token, *args): return worksheet.write_string(row, col, token, *args)
Note, you don’t have to explicitly handle A1
style cell ranges. These will
be converted to row and column values prior to your function being called.
You can also make use of the row
and col
parameters to control the
logic of the function. Say for example you wanted to hide/replace user
passwords with ‘****’ when writing string data. If your data was
structured so that the password data was in the second column, apart from the
header row, you could write a handler function like this:
def hide_password(worksheet, row, col, string, format=None): if col == 1 and row > 0: return worksheet.write_string(row, col, '****', format) else: return worksheet.write_string(row, col, string, format)
The return value of write handler functions
Functions used in the add_write_handler()
method should return one of
the following values:
None
: to indicate that control is return to the parentwrite()
method to continue as normal. This is used if your handler function logic
decides that you don’t need to handle the matched token.- The return value of the called
write_xxx()
function. This is generally 0
for no error and a negative number for errors. This causes an immediate
return from the callingwrite()
method with the return value that was
passed back.
For example, say you wanted to ignore NaN
values in your data since Excel
doesn’t support them. You could create a handler function like the following
that matched against floats and which wrote a blank cell if it was a NaN
or else just returned to write()
to continue as normal:
def ignore_nan(worksheet, row, col, number, format=None): if math.isnan(number): return worksheet.write_blank(row, col, None, format) else: # Return control to the calling write() method. return None
If you wanted to just drop the NaN
values completely and not add any
formatting to the cell you could just return 0, for no error:
def ignore_nan(worksheet, row, col, number, format=None): if math.isnan(number): return 0 else: # Return control to the calling write() method. return None
Содержание
- How to Convert Dictionary to Excel in Python
- How to convert Dictionary to excel in Python
- Convert Dictionary to Excel in Python
- Convert List of Dictionary to Excel in Python
- Conclusion
- How to write a Dictionary to Excel in Python
- 2 Answers 2
- Linked
- Related
- Hot Network Questions
- Subscribe to RSS
- Export a simple Dictionary into Excel file in python
- 3 Answers 3
- Linked
- Related
- Hot Network Questions
- Subscribe to RSS
- Sheet: Data conversion¶
- How to obtain records from an excel sheet¶
- How to save an python array as an excel file¶
- How to save an python array as a csv file with special delimiter¶
- How to get a dictionary from an excel sheet¶
- How to obtain a dictionary from a multiple sheet book¶
- How to save a dictionary of two dimensional array as an excel file¶
- How to import an excel sheet to a database using SQLAlchemy¶
- How to open an xls file and save it as csv¶
- How to open an xls file and save it as xlsx¶
- How to open a xls multiple sheet excel book and save it as csv¶
- Working with and Writing Data
- Writing data to a worksheet cell
- Writing unicode data
- Writing lists of data
- Writing dicts of data
- Writing dataframes
- Writing user defined types
- How the write handler feature works
- The syntax of write handler functions
- The return value of write handler functions
- Write handler examples
How to Convert Dictionary to Excel in Python
In this article, you will see everything about how to convert Dictionary to Excel in Python with the help of examples. Most of the time you will need to convert Python dictionaries or a list of Python dictionaries into excel. Then this article is going to be very helpful for you.
Prerequisites
Before going further into this article you will need to install the following packages using the pip command, If you have already installed then you can ignore them.
Headings of Contents
How to convert Dictionary to excel in Python
Here we will see a total of two ways to convert Python dictionaries into excel. The first is converting a single dictionary to excel and the second will be converting a list of dictionaries into excel.
Convert Dictionary to Excel in Python
Here I’m gonna convert only a single Python Dictionary to an excel file using the Python Pandas library.
In this example, we will see how to convert the Python dictionary to excel using the Python pandas module.
Example: Convert a dictionary to excel
After the above code is executed successfully, students.xlsx will create.
Convert List of Dictionary to Excel in Python
Sometimes you may want to convert the list of Python dictionaries to an Excel file. then again, you can follow the below approach.
Most of the time you have a large list of dictionaries and you want to convert them into excel, then it is also possible, Let’s see how can you do that.
Example: Convert a list of dictionaries to excel
Output
Conclusion
So we have seen all about how to convert a dictionary to excel in Python with the help of examples. This is one of the most important especially when you are generating reports from large dictionaries into an excel file because dictionaries are not understandable by non-techie guys so you have an option to convert it into an excel file.
I hope this article will help you. if you like this article, please share and keep visiting for further interesting articles.
Related Articles:-
Thanks for your valuable time… 🙏🙏
Источник
How to write a Dictionary to Excel in Python
I have the following dictionary in python that represents a From — To Distance Matrix.
Is it possible to output this matrix into excel or to a csv file so that it has the following format? I have looked into using csv.writer and csv.DictWriter but can not produce the desired output.
2 Answers 2
You may create a pandas dataframe from that dict, then save to CSV or Excel:
Probably not the most minimal result, but pandas would solve this marvellously (and if you’re doing data analysis of any kind, I can highly recommend pandas!).
Your data is already in a perfectformat for bringing into a Dataframe
but the output you want is this Transposed, so:
where T returns the transpose of the Dataframe.
Linked
Hot Network Questions
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.3.20.43325
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Источник
Export a simple Dictionary into Excel file in python
I am new to python. I have a simple dictionary for which the key and values are as follows
i need to get them in a excel sheet as follows
I have a very big dictionary.
3 Answers 3
You can use pandas.
This will write the contents of the dictionary to output.csv . The first column will contain the keys, the second will contain the values.
You can open the csv with excel and save it to any format you’d like.
As an extension to @Daniel Timberlake‘s answer, here’s what I found worked for me. I simply wanted to save a list of dict object (rows) to a CSV file, which could then later be converted to .xlsx format if needed.
Linked
Hot Network Questions
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.3.20.43325
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Источник
Sheet: Data conversion¶
How to obtain records from an excel sheet¶
Suppose you want to process the following excel data :
Here are the example code:
How to save an python array as an excel file¶
Suppose you have the following array:
And here is the code to save it as an excel file
Let’s verify it:
How to save an python array as a csv file with special delimiter¶
Suppose you have the following array:
And here is the code to save it as an excel file
Let’s verify it:
How to get a dictionary from an excel sheet¶
Suppose you have a csv, xls, xlsx file as the following:
The following code will give you data series in a dictionary:
Please note that my_dict is an OrderedDict.
How to obtain a dictionary from a multiple sheet book¶
Suppose you have a multiple sheet book as the following:
Here is the code to obtain those sheets as a single dictionary:
How to save a dictionary of two dimensional array as an excel file¶
Suppose you want to save the below dictionary to an excel file
Here is the code:
If you want to preserve the order of sheets in your dictionary, you have to pass on an ordered dictionary to the function itself. For example:
Let’s verify its order:
Please notice that “Sheet 2” is the first item in the book_dict, meaning the order of sheets are preserved.
How to import an excel sheet to a database using SQLAlchemy¶
You can find the complete code of this example in examples folder on github
Before going ahead, let’s import the needed components and initialize sql engine and table base:
Let’s suppose we have the following database model:
Let’s create the table:
Now here is a sample excel file to be saved to the table:
Here is the code to import it:
Done it. It is that simple. Let’s verify what has been imported to make sure.
How to open an xls file and save it as csv¶
Suppose we want to save previous used example вЂbirth.xls’ as a csv file
Again it is really simple. Let’s verify what we have gotten:
Please note that csv(comma separate value) file is pure text file. Formula, charts, images and formatting in xls file will disappear no matter which transcoding tool you use. Hence, pyexcel is a quick alternative for this transcoding job.
How to open an xls file and save it as xlsx¶
Formula, charts, images and formatting in xls file will disappear as pyexcel does not support Formula, charts, images and formatting.
Let use previous example and save it as ods instead
Again let’s verify what we have gotten:
How to open a xls multiple sheet excel book and save it as csv¶
Well, you write similar codes as before but you will need to use save_book_as() function.
© Copyright 2014-2022 Onni Software Ltd. Revision 376aed4e .
Источник
Working with and Writing Data
The following sections explain how to write various types of data to an Excel worksheet using XlsxWriter.
Writing data to a worksheet cell
The worksheet write() method is the most common means of writing Python data to cells based on its type:
The write() method uses the type() of the data to determine which specific method to use for writing the data. These methods then map some basic Python types to corresponding Excel types. The mapping is as follows:
Python type | Excel type | Worksheet methods |
---|---|---|
int | Number | write() , write_number() |
long | ||
float | ||
Decimal | ||
Fraction | ||
basestring | String | write() , write_string() |
str | ||
unicode | ||
None | String (blank) | write() , write_blank() |
datetime.date | Number | write() , write_datetime() |
datetime.datetime | ||
datetime.time | ||
datetime.timedelta | ||
bool | Boolean | write() , write_boolean() |
The write() method also handles a few other Excel types that are encoded as Python strings in XlsxWriter:
Pseudo-type | Excel type | Worksheet methods |
---|---|---|
formula string | Formula | write() , write_formula() |
url string | URL | write() , write_url() |
It should be noted that Excel has a very limited set of types to map to. The Python types that the write() method can handle can be extended as explained in the Writing user defined types section below.
Writing unicode data
Unicode data in Excel is encoded as UTF-8. XlsxWriter also supports writing UTF-8 data. This generally requires that your source file is UTF-8 encoded:
Alternatively, you can read data from an encoded file, convert it to UTF-8 during reading and then write the data to an Excel file. See Example: Unicode — Polish in UTF-8 and Example: Unicode — Shift JIS .
Writing lists of data
Writing compound data types such as lists with XlsxWriter is done the same way it would be in any other Python program: with a loop. The Python enumerate() function is also very useful in this context:
Or if you wanted to write this horizontally as a row:
For a list of lists structure you would use two loop levels:
The worksheet class has two utility functions called write_row() and write_column() which are basically a loop around the write() method:
Writing dicts of data
Unlike lists there is no single simple way to write a Python dictionary to an Excel worksheet using Xlsxwriter. The method will depend of the structure of the data in the dictionary. Here is a simple example for a simple data structure:
Writing dataframes
The best way to deal with dataframes or complex data structure is to use Python Pandas. Pandas is a Python data analysis library. It can read, filter and re-arrange small and large data sets and output them in a range of formats including Excel.
To use XlsxWriter with Pandas you specify it as the Excel writer engine:
The output from this would look like the following:
For more information on using Pandas with XlsxWriter see Working with Pandas and XlsxWriter .
Writing user defined types
As shown in the first section above, the worksheet write() method maps the main Python data types to Excel’s data types. If you want to write an unsupported type then you can either avoid write() and map the user type in your code to one of the more specific write methods or you can extend it using the add_write_handler() method. This can be, occasionally, more convenient then adding a lot of if/else logic to your code.
As an example, say you wanted to modify write() to automatically write uuid types as strings. You would start by creating a function that takes the uuid, converts it to a string and then writes it using write_string() :
You could then add a handler that matches the uuid type and calls your user defined function:
Then you can use write() without further modification:
Multiple callback functions can be added using add_write_handler() but only one callback action is allowed per type. However, it is valid to use the same callback function for different types:
How the write handler feature works
The write() method is mainly a large if() statement that checks the type() of the input value and calls the appropriate worksheet method to write the data. The add_write_handler() method works by injecting additional type checks and associated actions into this if() statement.
Here is a simplified version of the write() method:
The syntax of write handler functions
Functions used in the add_write_handler() method should have the following method signature/parameters:
The function will be passed a worksheet instance, an integer row and col value, a token that matches the type added to add_write_handler() and some additional parameters. Usually the additional parameter(s) will only be a cell format instance. However, if you need to handle other additional parameters, such as those passed to write_url() then you can have more generic handling like this:
Note, you don’t have to explicitly handle A1 style cell ranges. These will be converted to row and column values prior to your function being called.
You can also make use of the row and col parameters to control the logic of the function. Say for example you wanted to hide/replace user passwords with ‘****’ when writing string data. If your data was structured so that the password data was in the second column, apart from the header row, you could write a handler function like this:
The return value of write handler functions
Functions used in the add_write_handler() method should return one of the following values:
- None : to indicate that control is return to the parent write() method to continue as normal. This is used if your handler function logic decides that you don’t need to handle the matched token.
- The return value of the called write_xxx() function. This is generally 0 for no error and a negative number for errors. This causes an immediate return from the calling write() method with the return value that was passed back.
For example, say you wanted to ignore NaN values in your data since Excel doesn’t support them. You could create a handler function like the following that matched against floats and which wrote a blank cell if it was a NaN or else just returned to write() to continue as normal:
If you wanted to just drop the NaN values completely and not add any formatting to the cell you could just return 0, for no error:
Write handler examples
See the following, more complete, examples of handling user data types:
© Copyright 2013-2023, John McNamara.
Created using Sphinx 1.8.6.
Источник