How to write an Excel file in Python


In this tutorial, we will learn how to write an excel file in Python.  At the end of this tutorial, you will learn how to open an Microsoft Excel file, write the data into particular column in a particular sheet of the Excel file.


Let us assume that you would like to create an Excel file which consists of 2 columns Name and Age. We will develop the Python code to write the data into an Excel file. And finally we will compute the average age of all the students.


Step 1 : The first step is to import the xlwt library. We use xlwt package to read the data from Excel spreadsheets.  If xlwt library is not installed, you can download from here.

Step 2 : In this step, we will create a workbook and an Excel sheet “ExperimentSheet”. Notice the parameter “cell_overwrite_ok” which is set to True. This is necessary if you have to write the existing cell more than once and Python would not raise an exception.


Step 3 : Add the Header : As seen from the Excel sheet, we need to first add two headers, “Name” and “Age” in cell A1 and  B1, respectively.


Similarly, we need to add the name and age of the students. Let us assume we have an array of array consisting of Name and age in Python variable “data”.


Step 4 : Computing the Average

We need to add the row AVERAGE on column A below all the names of all the students. We need to use the Excel Average Formula AVERAGE(B2:B8).


Notice the function excel_style() which converts number to Excel column name.


The last step is to save the Excel file.




The complete Python source can be downloaded from here. Please note, that the code is tested using Python 2.7 . If you are using Python 3.3, you might have to do some minor changes in the code.

I hope, you find this article very useful. If you have any doubts or have any comments concerning this tutorial, Please leave a comment or contact me. I would be glad to help.


Kiran Chandrashekhar

Hey, Thanks for dropping by. My name is Kiran Chandrashekhar. I am a full-time software freelancer. I love Maths and Mathematical Shortcuts. Numbers fascinate me. I will be posting articles on Mathematical Shortcuts, Software Tips, Programming Tips in this website. I love teaching students preparing for various competitive examinations. Read my complete story.

Leave a Reply

Your email address will not be published. Required fields are marked *

Protected by WP Anti Spam