Watch Now This tutorial has a related Clip course created by the Real Python team. Watch it together with the written tutorial to tát deepen your understanding: Editing Excel Spreadsheets in Python With openpyxl

Excel spreadsheets are one of those things you might have to tát khuyến mãi with at some point. Either it’s because your quấn loves them or because marketing needs them, you might have to tát learn how to tát work with spreadsheets, and that’s when knowing openpyxl comes in handy!

Bạn đang xem: openpyxl

Spreadsheets are a very intuitive and user-friendly way to tát manipulate large datasets without any prior technical background. That’s why they’re still so sánh commonly used today.

In this article, you’ll learn how to tát use openpyxl to:

  • Manipulate Excel spreadsheets with confidence
  • Extract information from spreadsheets
  • Create simple or more complex spreadsheets, including adding styles, charts, and so sánh on

This article is written for intermediate developers who have a pretty good knowledge of Python data structures, such as dicts and lists, but also feel comfortable around OOP and more intermediate level topics.

Before You Begin

If you ever get asked to tát extract some data from a database or log tệp tin into an Excel spreadsheet, or if you often have to tát convert an Excel spreadsheet into some more usable programmatic size, then this tutorial is perfect for you. Let’s jump into the openpyxl caravan!

Practical Use Cases

First things first, when would you need to tát use a package lượt thích openpyxl in a real-world scenario? You’ll see a few examples below, but really, there are hundreds of possible scenarios where this knowledge could come in handy.

Importing New Products Into a Database

You are responsible for tech in an online store company, and your quấn doesn’t want to tát pay for a cool and expensive CMS system.

Every time they want to tát add new products to tát the online store, they come to tát you with an Excel spreadsheet with a few hundred rows and, for each of them, you have the product name, mô tả tìm kiếm, price, and so sánh forth.

Now, to tát import the data, you’ll have to tát iterate over each spreadsheet row and add each product to tát the online store.

Exporting Database Data Into a Spreadsheet

Say you have a Database table where you record all your users’ information, including name, phone number, tin nhắn address, and so sánh forth.

Now, the Marketing team wants to tát liên hệ all users to tát give them some discounted offer or promotion. However, they don’t have access to tát the Database, or they don’t know how to tát use SQL to tát extract that information easily.

What can you vì thế to tát help? Well, you can make a quick script using openpyxl that iterates over every single User record and puts all the essential information into an Excel spreadsheet.

That’s gonna earn you an extra slice of cake at your company’s next birthday party!

Appending Information to tát an Existing Spreadsheet

You may also have to tát open a spreadsheet, read the information in it and, according to tát some business logic, append more data to tát it.

For example, using the online store scenario again, say you get an Excel spreadsheet with a list of users and you need to tát append to tát each row the total amount they’ve spent in your store.

This data is in the Database and, in order to tát vì thế this, you have to tát read the spreadsheet, iterate through each row, fetch the total amount spent from the Database and then write back to tát the spreadsheet.

Not a problem for openpyxl!

Learning Some Basic Excel Terminology

Here’s a quick list of basic terms you’ll see when you’re working with Excel spreadsheets:

Term Explanation
Spreadsheet or Workbook A Spreadsheet is the main tệp tin you are creating or working with.
Worksheet or Sheet A Sheet is used to tát split different kinds of nội dung within the same spreadsheet. A Spreadsheet can have one or more Sheets.
Column A Column is a vertical line, and it’s represented by an uppercase letter: A.
Row A Row is a horizontal line, and it’s represented by a number: 1.
Cell A Cell is a combination of Column and Row, represented by both an uppercase letter and a number: A1.

Getting Started With openpyxl

Now that you’re aware of the benefits of a tool lượt thích openpyxl, let’s get down to tát it and start by installing the package. For this tutorial, you should use Python 3.7 and openpyxl 2.6.2. To install the package, you can vì thế the following:

After you install the package, you should be able to tát create a super simple spreadsheet with the following code:

The code above should create a tệp tin called hello_world.xlsx in the thư mục you are using to tát lập cập the code. If you open that tệp tin with Excel you should see something lượt thích this:

A Simple Hello World Spreadsheet

Woohoo, your first spreadsheet created!

Reading Excel Spreadsheets With openpyxl

Let’s start with the most essential thing one can vì thế with a spreadsheet: read it.

You’ll go from a straightforward approach to tát reading a spreadsheet to tát more complex examples where you read the data and convert it into more useful Python structures.

Dataset for This Tutorial

Before you dive deep into some code examples, you should download this sample dataset and store it somewhere as sample.xlsx:

This is one of the datasets you’ll be using throughout this tutorial, and it’s a spreadsheet with a sample of real data from Amazon’s online product reviews. This dataset is only a tiny fraction of what Amazon provides, but for testing purposes, it’s more than thở enough.

A Simple Approach to tát Reading an Excel Spreadsheet

Finally, let’s start reading some spreadsheets! To begin with, open our sample spreadsheet:

In the code above, you first open the spreadsheet sample.xlsx using load_workbook(), and then you can use workbook.sheetnames to tát see all the sheets you have available to tát work with. After that, selects the first available sheet and, in this case, you can see that it selects Sheet 1 automatically. Using these methods is the mặc định way of opening a spreadsheet, and you’ll see it many times during this tutorial.

Now, after opening a spreadsheet, you can easily retrieve data from it lượt thích this:

To return the actual value of a cell, you need to tát vì thế .value. Otherwise, you’ll get the main Cell object. You can also use the method .cell() to tát retrieve a cell using index notation. Remember to tát add .value to tát get the actual value and not a Cell object:

You can see that the results returned are the same, no matter which way you decide to tát go with. However, in this tutorial, you’ll be mostly using the first approach: ["A1"].

The above shows you the quickest way to tát open a spreadsheet. However, you can pass additional parameters to tát change the way a spreadsheet is loaded.

Additional Reading Options

There are a few arguments you can pass to tát load_workbook() that change the way a spreadsheet is loaded. The most important ones are the following two Booleans:

  1. read_only loads a spreadsheet in read-only mode allowing you to tát open very large Excel files.
  2. data_only ignores loading formulas and instead loads only the resulting values.

Importing Data From a Spreadsheet

Now that you’ve learned the basics about loading a spreadsheet, it’s about time you get to tát the fun part: the iteration and actual usage of the values within the spreadsheet.

This section is where you’ll learn all the different ways you can iterate through the data, but also how to tát convert that data into something usable and, more importantly, how to tát vì thế it in a Pythonic way.

Iterating Through the Data

There are a few different ways you can iterate through the data depending on your needs.

You can slice the data with a combination of columns and rows:

You can get ranges of rows or columns:

You’ll notice that all of the above examples return a tuple. If you want to tát refresh your memory on how to tát handle tuples in Python, kiểm tra out the article on Lists and Tuples in Python.

There are also multiple ways of using normal Python generators to tát go through the data. The main methods you can use to tát achieve this are:

  • .iter_rows()
  • .iter_cols()

Both methods can receive the following arguments:

  • min_row
  • max_row
  • min_col
  • max_col

These arguments are used to tát phối boundaries for the iteration:

You’ll notice that in the first example, when iterating through the rows using .iter_rows(), you get one tuple element per row selected. While when using .iter_cols() and iterating through columns, you’ll get one tuple per column instead.

One additional argument you can pass to tát both methods is the Boolean values_only. When it’s phối to tát True, the values of the cell are returned, instead of the Cell object:

If you want to tát iterate through the whole dataset, then you can also use the attributes .rows or .columns directly, which are shortcuts to tát using .iter_rows() and .iter_cols() without any arguments:

These shortcuts are very useful when you’re iterating through the whole dataset.

Manipulate Data Using Python’s Default Data Structures

Now that you know the basics of iterating through the data in a workbook, let’s look at smart ways of converting that data into Python structures.

As you saw earlier, the result from all iterations comes in the size of tuples. However, since a tuple is nothing more than thở a list that’s immutable, you can easily access its data and transform it into other structures.

For example, say you want to tát extract product information from the sample.xlsx spreadsheet and into a dictionary where each key is a product ID.

A straightforward way to tát vì thế this is to tát iterate over all the rows, pick the columns you know are related to tát product information, and then store that in a dictionary. Let’s code this out!

First of all, have a look at the headers and see what information you care most about:

This code returns a list of all the column names you have in the spreadsheet. To start, grab the columns with names:

  • product_id
  • product_parent
  • product_title
  • product_category

Lucky for you, the columns you need are all next to tát each other so sánh you can use the min_column and max_column to tát easily get the data you want:

Nice! Now that you know how to tát get all the important product information you need, let’s put that data into a dictionary:

The code above returns a JSON similar to tát this:

Here you can see that the output is trimmed to tát 2 products only, but if you lập cập the script as it is, then you should get 98 products.

Convert Data Into Python Classes

To finalize the reading section of this tutorial, let’s dive into Python classes and see how you could improve on the example above and better structure the data.

For this, you’ll be using the new Python Data Classes that are available from Python 3.7. If you’re using an older version of Python, then you can use the mặc định Classes instead.

So, first things first, let’s look at the data you have and decide what you want to tát store and how you want to tát store it.

As you saw right at the start, this data comes from Amazon, and it’s a list of product reviews. You can kiểm tra the list of all the columns and their meaning on Amazon.

There are two significant elements you can extract from the data available:

  1. Products
  2. Reviews

A Product has:

  • ID
  • Title
  • Parent
  • Category

The Review has a few more fields:

  • ID
  • Customer ID
  • Stars
  • Headline
  • Body
  • Date

You can ignore a few of the review fields to tát make things a bit simpler.

So, a straightforward implementation of these two classes could be written in a separate tệp tin

After defining your data classes, you need to tát convert the data from the spreadsheet into these new structures.

Before doing the conversion, it’s worth looking at our header again and creating a mapping between columns and the fields you need:

Let’s create a tệp tin where you have a list of all the field names and their column location (zero-indexed) on the spreadsheet:

You don’t necessarily have to tát vì thế the mapping above. It’s more for readability when parsing the row data, so sánh you don’t kết thúc up with a lot of magic numbers lying around.

Finally, let’s look at the code needed to tát parse the spreadsheet data into a list of product and review objects:

After you lập cập the code above, you should get some output lượt thích this:

That’s it! Now you should have the data in a very simple and digestible class format, and you can start thinking of storing this in a Database or any other type of data storage you lượt thích.

Using this kind of OOP strategy to tát parse spreadsheets makes handling the data much simpler later on.

Appending New Data

Before you start creating very complex spreadsheets, have a quick look at an example of how to tát append data to tát an existing spreadsheet.

Go back to tát the first example spreadsheet you created (hello_world.xlsx) and try opening it and appending some data to tát it, lượt thích this:

Et voilà, if you open the new hello_world_append.xlsx spreadsheet, you’ll see the following change:

Appending Data to tát a Spreadsheet

Notice the additional writing ;) on cell C1.

Writing Excel Spreadsheets With openpyxl

There are a lot of different things you can write to tát a spreadsheet, from simple text or number values to tát complex formulas, charts, or even images.

Let’s start creating some spreadsheets!

Creating a Simple Spreadsheet

Previously, you saw a very quick example of how to tát write “Hello world!” into a spreadsheet, so sánh you can start with that:

The highlighted lines in the code above are the most important ones for writing. In the code, you can see that:

  • Line 5 shows you how to tát create a new empty workbook.
  • Lines 8 and 9 show you how to tát add data to tát specific cells.
  • Line 11 shows you how to tát save the spreadsheet when you’re done.

Even though these lines above can be straightforward, it’s still good to tát know them well for when things get a bit more complicated.

One thing you can vì thế to tát help with coming code examples is add the following method to tát your Python tệp tin or console:

It makes it easier to tát print all of your spreadsheet values by just calling print_rows().

Basic Spreadsheet Operations

Before you get into the more advanced topics, it’s good for you to tát know how to tát manage the most simple elements of a spreadsheet.

Adding and Updating Cell Values

You already learned how to tát add values to tát a spreadsheet lượt thích this:

There’s another way you can vì thế this, by first selecting a cell and then changing its value:

The new value is only stored into the spreadsheet once you Điện thoại tư vấn

The openpyxl creates a cell when adding a value, if that cell didn’t exist before:

As you can see, when trying to tát add a value to tát cell B10, you kết thúc up with a tuple with 10 rows, just so sánh you can have that test value.

Managing Rows and Columns

One of the most common things you have to tát vì thế when manipulating spreadsheets is adding or removing rows and columns. The openpyxl package allows you to tát vì thế that in a very straightforward way by using the methods:

  • .insert_rows()
  • .delete_rows()
  • .insert_cols()
  • .delete_cols()

Every single one of those methods can receive two arguments:

  1. idx
  2. amount

Using our basic hello_world.xlsx example again, let’s see how these methods work:

The only thing you need to tát remember is that when inserting new data (rows or columns), the insertion happens before the idx parameter.

So, if you vì thế insert_rows(1), it inserts a new row before the existing first row.

It’s the same for columns: when you Điện thoại tư vấn insert_cols(2), it inserts a new column right before the already existing second column (B).

However, when deleting rows or columns, .delete_... deletes data starting from the index passed as an argument.

For example, when doing delete_rows(2) it deletes row 2, and when doing delete_cols(3) it deletes the third column (C).

Managing Sheets

Sheet management is also one of those things you might need to tát know, even though it might be something that you don’t use that often.

If you look back at the code examples from this tutorial, you’ll notice the following recurring piece of code:

This is the way to tát select the mặc định sheet from a spreadsheet. However, if you’re opening a spreadsheet with multiple sheets, then you can always select a specific one lượt thích this:

You can also change a sheet title very easily:

If you want to tát create or delete sheets, then you can also vì thế that with .create_sheet() and .remove():

One other thing you can vì thế is make duplicates of a sheet using copy_worksheet():

If you open your spreadsheet after saving the above code, you’ll notice that the sheet Products Copy is a duplicate of the sheet Products.

Freezing Rows and Columns

Something that you might want to tát vì thế when working with big spreadsheets is to tát freeze a few rows or columns, so sánh they remain visible when you scroll right or down.

Freezing data allows you to tát keep an eye on important rows or columns, regardless of where you scroll in the spreadsheet.

Again, openpyxl also has a way to tát accomplish this by using the worksheet freeze_panes attribute. For this example, go back to tát our sample.xlsx spreadsheet and try doing the following:

If you open the sample_frozen.xlsx spreadsheet in your favorite spreadsheet editor, you’ll notice that row 1 and columns A and B are frozen and are always visible no matter where you navigate within the spreadsheet.

Xem thêm: ăn hết giới giải trí

This feature is handy, for example, to tát keep headers within sight, so sánh you always know what each column represents.

Here’s how it looks in the editor:

Example Spreadsheet With Frozen Rows and Columns

Notice how you’re at the kết thúc of the spreadsheet, and yet, you can see both row 1 and columns A and B.

Adding Filters

You can use openpyxl to tát add filters and sorts to tát your spreadsheet. However, when you open the spreadsheet, the data won’t be rearranged according to tát these sorts and filters.

At first, this might seem lượt thích a pretty useless feature, but when you’re programmatically creating a spreadsheet that is going to tát be sent and used by somebody else, it’s still nice to tát at least create the filters and allow people to tát use it afterward.

The code below is an example of how you would add some filters to tát our existing sample.xlsx spreadsheet:

You should now see the filters created when opening the spreadsheet in your editor:

Example Spreadsheet With Filters

You don’t have to tát use sheet.dimensions if you know precisely which part of the spreadsheet you want to tát apply filters to tát.

Adding Formulas

Formulas (or formulae) are one of the most powerful features of spreadsheets.

They gives you the power to tát apply specific mathematical equations to tát a range of cells. Using formulas with openpyxl is as simple as editing the value of a cell.

You can see the list of formulas supported by openpyxl:

Let’s add some formulas to tát our sample.xlsx spreadsheet.

Starting with something easy, let’s kiểm tra the average star rating for the 99 reviews within the spreadsheet:

If you open the spreadsheet now and go to tát cell P2, you should see that its value is: 4.18181818181818. Have a look in the editor:

Example Spreadsheet With Average Formula

You can use the same methodology to tát add any formulas to tát your spreadsheet. For example, let’s count the number of reviews that had helpful votes:

You should get the number 21 on your P3 spreadsheet cell lượt thích so:

Example Spreadsheet With Average and CountIf Formula

You’ll have to tát make sure that the strings within a formula are always in double quotes, so sánh you either have to tát use single quotes around the formula lượt thích in the example above or you’ll have to tát escape the double quotes inside the formula: "=COUNTIF(I2:I100, \">0\")".

There are a ton of other formulas you can add to tát your spreadsheet using the same procedure you tried above. Give it a go yourself!

Adding Styles

Even though styling a spreadsheet might not be something you would vì thế every day, it’s still good to tát know how to tát vì thế it.

Using openpyxl, you can apply multiple styling options to tát your spreadsheet, including fonts, borders, colors, and so sánh on. Have a look at the openpyxl documentation to tát learn more.

You can also choose to tát either apply a style directly to tát a cell or create a template and reuse it to tát apply styles to tát multiple cells.

Let’s start by having a look at simple cell styling, using our sample.xlsx again as the base spreadsheet:

If you open your spreadsheet now, you should see quite a few different styles on the first 5 cells of column A:

Example Spreadsheet With Simple Cell Styles

There you go. You got:

  • A2 with the text in bold
  • A3 with the text in red and bigger fonts size
  • A4 with the text centered
  • A5 with a square border around the text

You can also combine styles by simply adding them to tát the cell at the same time:

Have a look at cell A6 here:

Example Spreadsheet With Coupled Cell Styles

When you want to tát apply multiple styles to tát one or several cells, you can use a NamedStyle class instead, which is lượt thích a style template that you can use over and over again. Have a look at the example below:

If you open the spreadsheet now, you should see that its first row is bold, the text is aligned to tát the center, and there’s a small bottom border! Have a look below:

Example Spreadsheet With Named Styles

As you saw above, there are many options when it comes to tát styling, and it depends on the use case, so sánh feel không tính tiền to tát kiểm tra openpyxl documentation and see what other things you can vì thế.

Conditional Formatting

This feature is one of my personal favorites when it comes to tát adding styles to tát a spreadsheet.

It’s a much more powerful approach to tát styling because it dynamically applies styles according to tát how the data in the spreadsheet changes.

In a nutshell, conditional formatting allows you to tát specify a list of styles to tát apply to tát a cell (or cell range) according to tát specific conditions.

For example, a widespread use case is to tát have a balance sheet where all the negative totals are in red, and the positive ones are in green. This formatting makes it much more efficient to tát spot good vs bad periods.

Without further ado, let’s pick our favorite spreadsheet—sample.xlsx—and add some conditional formatting.

You can start by adding a simple one that adds a red background to tát all reviews with less than thở 3 stars:

Now you’ll see all the reviews with a star rating below 3 marked with a red background:

Example Spreadsheet With Simple Conditional Formatting

Code-wise, the only things that are new here are the objects DifferentialStyle and Rule:

  • DifferentialStyle is quite similar to tát NamedStyle, which you already saw above, and it’s used to tát aggregate multiple styles such as fonts, borders, alignment, and so sánh forth.
  • Rule is responsible for selecting the cells and applying the styles if the cells match the rule’s logic.

Using a Rule object, you can create numerous conditional formatting scenarios.

However, for simplicity sake, the openpyxl package offers 3 built-in formats that make it easier to tát create a few common conditional formatting patterns. These built-ins are:

  • ColorScale
  • IconSet
  • DataBar

The ColorScale gives you the ability to tát create color gradients:

Now you should see a color gradient on column H, from red to tát green, according to tát the star rating:

Example Spreadsheet With Màu sắc Scale Conditional Formatting

You can also add a third color and make two gradients instead:

This time, you’ll notice that star ratings between 1 and 3 have a gradient from red to tát yellow, and star ratings between 3 and 5 have a gradient from yellow to tát green:

Example Spreadsheet With 2 Màu sắc Scales Conditional Formatting

The IconSet allows you to tát add an icon to tát the cell according to tát its value:

You’ll see a colored arrow next to tát the star rating. This arrow is red and points down when the value of the cell is 1 and, as the rating gets better, the arrow starts pointing up and becomes green:

Example Spreadsheet With Icon Set Conditional Formatting

The openpyxl package has a full list of other icons you can use, besides the arrow.

Finally, the DataBar allows you to tát create progress bars:

You’ll now see a green progress bar that gets fuller the closer the star rating is to tát the number 5:

Example Spreadsheet With Data Bar Conditional Formatting

As you can see, there are a lot of cool things you can vì thế with conditional formatting.

Here, you saw only a few examples of what you can achieve with it, but kiểm tra the openpyxl documentation to tát see a bunch of other options.

Adding Images

Even though images are not something that you’ll often see in a spreadsheet, it’s quite cool to tát be able to tát add them. Maybe you can use it for branding purposes or to tát make spreadsheets more personal.

To be able to tát load images to tát a spreadsheet using openpyxl, you’ll have to tát install Pillow:

Apart from that, you’ll also need an image. For this example, you can grab the Real Python logo below and convert it from .webp to tát .png using an online converter such as, save the final tệp tin as logo.png, and copy it to tát the root thư mục where you’re running your examples:

Real Python Logo

Afterward, this is the code you need to tát import that image into the hello_word.xlsx spreadsheet:

You have an image on your spreadsheet! Here it is:

Example Spreadsheet With Image

The image’s left top corner is on the cell you chose, in this case, A3.

Adding Pretty Charts

Another powerful thing you can vì thế with spreadsheets is create an incredible variety of charts.

Charts are a great way to tát visualize and understand loads of data quickly. There are a lot of different chart types: bar chart, pie chart, line chart, and so sánh on. openpyxl has tư vấn for a lot of them.

Here, you’ll see only a couple of examples of charts because the theory behind it is the same for every single chart type:

For any chart you want to tát build, you’ll need to tát define the chart type: BarChart, LineChart, and so sánh forth, plus the data to tát be used for the chart, which is called Reference.

Before you can build your chart, you need to tát define what data you want to tát see represented in it. Sometimes, you can use the dataset as is, but other times you need to tát mas sa the data a bit to tát get additional information.

Let’s start by building a new workbook with some sample data:

Now you’re going to tát start by creating a bar chart that displays the total number of sales per product:

There you have it. Below, you can see a very straightforward bar chart showing the difference between online product sales online and in-store product sales:

Example Spreadsheet With Bar Chart

Like with images, the top left corner of the chart is on the cell you added the chart to tát. In your case, it was on cell E2.

Try creating a line chart instead, changing the data a bit:

With the above code, you’ll be able to tát generate some random data regarding the sales of 3 different products across a whole year.

Once that’s done, you can very easily create a line chart with the following code:

Here’s the outcome of the above piece of code:

Example Spreadsheet With Line Chart

One thing to tát keep in mind here is the fact that you’re using from_rows=True when adding the data. This argument makes the chart plot row by row instead of column by column.

In your sample data, you see that each product has a row with 12 values (1 column per month). That’s why you use from_rows. If you don’t pass that argument, by mặc định, the chart tries to tát plot by column, and you’ll get a month-by-month comparison of sales.

Another difference that has to tát vì thế with the above argument change is the fact that our Reference now starts from the first column, min_col=1, instead of the second one. This change is needed because the chart now expects the first column to tát have the titles.

There are a couple of other things you can also change regarding the style of the chart. For example, you can add specific categories to tát the chart:

Add this piece of code before saving the workbook, and you should see the month names appearing instead of numbers:

Example Spreadsheet With Line Chart and Categories

Code-wise, this is a minimal change. But in terms of the readability of the spreadsheet, this makes it much easier for someone to tát open the spreadsheet and understand the chart straight away.

Another thing you can vì thế to tát improve the chart readability is to tát add an axis. You can vì thế it using the attributes x_axis and y_axis:

This will generate a spreadsheet lượt thích the below one:

Example Spreadsheet With Line Chart, Categories and Axis Titles

As you can see, small changes lượt thích the above make reading your chart a much easier and quicker task.

There is also a way to tát style your chart by using Excel’s mặc định ChartStyle property. In this case, you have to tát choose a number between 1 and 48. Depending on your choice, the colors of your chart change as well:

With the style selected above, all lines have some shade of orange:

Example Spreadsheet With Line Chart, Categories, Axis Titles and Style

There is no clear documentation on what each style number looks lượt thích, but this spreadsheet has a few examples of the styles available.

Here’s the full code used to tát generate the line chart with categories, axis titles, and style:

There are a lot more chart types and customization you can apply, so sánh be sure to tát kiểm tra out the package documentation on this if you need some specific formatting.

Convert Python Classes to tát Excel Spreadsheet

You already saw how to tát convert an Excel spreadsheet’s data into Python classes, but now let’s vì thế the opposite.

Let’s imagine you have a database and are using some Object-Relational Mapping (ORM) to tát map DB objects into Python classes. Now, you want to tát export those same objects into a spreadsheet.

Let’s assume the following data classes to tát represent the data coming from your database regarding product sales:

Now, let’s generate some random data, assuming the above classes are stored in a file:

By running this piece of code, you should get 5 products with 5 months of sales with a random quantity of sales for each month.

Now, to tát convert this into a spreadsheet, you need to tát iterate over the data and append it to tát the spreadsheet:

That’s it. That should allow you to tát create a spreadsheet with some data coming from your database.

However, why not use some of that cool knowledge you gained recently to tát add a chart as well to tát display that data more visually?

All right, then you could probably vì thế something lượt thích this:

Now we’re talking! Here’s a spreadsheet generated from database objects and with a chart and everything:

Example Spreadsheet With Conversion from Python Data Classes

That’s a great way for you to tát wrap up your new knowledge of charts!

Bonus: Working With Pandas

Even though you can use Pandas to tát handle Excel files, there are few things that you either can’t accomplish with Pandas or that you’d be better off just using openpyxl directly.

For example, some of the advantages of using openpyxl are the ability to tát easily customize your spreadsheet with styles, conditional formatting, and such.

But guess what, you don’t have to tát worry about picking. In fact, openpyxl has tư vấn for both converting data from a Pandas DataFrame into a workbook or the opposite, converting an openpyxl workbook into a Pandas DataFrame.

First things first, remember to tát install the pandas package:

Then, let’s create a sample DataFrame:

Now that you have some data, you can use .dataframe_to_rows() to tát convert it from a DataFrame into a worksheet:

You should see a spreadsheet that looks lượt thích this:

Example Spreadsheet With Data from Pandas Data Frame

If you want to tát add the DataFrame’s index, you can change index=True, and it adds each row’s index into your spreadsheet.

On the other hand, if you want to tát convert a spreadsheet into a DataFrame, you can also vì thế it in a very straightforward way lượt thích so:

Alternatively, if you want to tát add the correct headers and use the review ID as the index, for example, then you can also vì thế it lượt thích this instead:

Using indexes and columns allows you to tát access data from your DataFrame easily:

There you go, whether you want to tát use openpyxl to tát prettify your Pandas dataset or use Pandas to tát vì thế some hardcore algebra, you now know how to tát switch between both packages.


Phew, after that long read, you now know how to tát work with spreadsheets in Python! You can rely on openpyxl, your trustworthy companion, to:

Xem thêm: chien than tran quoc

  • Extract valuable information from spreadsheets in a Pythonic manner
  • Create your own spreadsheets, no matter the complexity level
  • Add cool features such as conditional formatting or charts to tát your spreadsheets

There are a few other things you can vì thế with openpyxl that might not have been covered in this tutorial, but you can always kiểm tra the package’s official documentation trang web to tát learn more about it. You can even venture into checking its source code and improving the package further.

Feel không tính tiền to tát leave any comments below if you have any questions, or if there’s any section you’d love to tát hear more about.

Watch Now This tutorial has a related Clip course created by the Real Python team. Watch it together with the written tutorial to tát deepen your understanding: Editing Excel Spreadsheets in Python With openpyxl