×

Writing to Excel using Python

Python is an Object-Oriented high-level language. Python has an English-like syntax, which is very easy to read and write codes. Python is an interpreted language which means that it uses an interpreter instead of the compiler to run the code.

The interpreted language is processed at the run time thus takes less time to run. Python is also interactive, so we can directly run programs in the terminal itself.

Sometimes, we need to handle excel sheets while working in Python because excel sheets can contain loads of data that we want to load and work with. We can perform multiple operations on excel sheets using the xlwt module.

We can use the write method to write an excel sheet in Python. In addition to the write method, there are many other methods and logic to handle excel files.

XlsxWriter module is used to write the excel files in the .xslx extension. We can create multiple worksheets using this module and write texts, numbers, and formulas for them. This module also supports adding images, charts, etc.

We can install the xlsx writer using the command below:

Pip install xlsxwriter

Let us see an example of how we can write data in specific cells. But before writing the code, we should keep in mind that rows and columns in Xlsxwriter are zero-indexed, i.e., the first cell is A1(0,0), B1(0,1)…. and so on.

importxlsxwriter


workbook = xlsxwriter.Workbook('Example.xlsx')
worksheet = workbook.add_worksheet()
row = 0
column = 0


content = ["Roahn", "Nikhil", "Roshan", "Mehak", "Mudit", "Muskaan", "Chandan"]
for item in content :
worksheet.write(row, column, item)


column+=1


workbook.close()

Output:

Running this code will create an excel sheet named Example.csv in the same directory with the content:

RoahnNikhilRoshanMehakMuditMuskaanChandan
Writing to Excel using Python

Writing Data one by one in Excel.

To write data cell by cell in a worksheet, use the code below:

importxlsxwriter


workbook = xlsxwriter.Workbook('Example2.xlsx')
worksheet = workbook.add_worksheet()


worksheet.write(0, 0, 123)     #Int
worksheet.write(1, 0, 123.45)  #Float
worksheet.write(2, 0, 'Rohan')  #String
worksheet.write(3, 0, None)     # None
worksheet.write(4, 0, True)     # bool


workbook.close()

Output

After running this code, you will be able to see this content in an excel file named Example2.xslx:

123
123.45
Rohan


TRUE
Writing to Excel using Python

As you can see, we have written different data types in different cells in this example. Write() method automatically determines the data type of the data inserted and uses the functions for that datatype to enter the value in a cell.

Writing using xlwt module.

We can also use the xlwt module to write data In excel sheets. To install the xlwt module write this command in your console:

Pip install xlwt

After installing the module, let us see how to create and write an excel file using this module.

importxlwt #importing module
fromxlwt import Workbook


# creating workbook
wb = Workbook()


sheet1 = wb.add_sheet('Sheet 1')


sheet1.write(1, 0, 'ISBT DEHRADUN')
sheet1.write(2, 0, 'SHASTRADHARA')
sheet1.write(3, 0, 'CLEMEN TOWN')
sheet1.write(4, 0, 'RAJPUR ROAD')
sheet1.write(5, 0, 'CLOCK TOWER')
sheet1.write(0, 1, 'ISBT DEHRADUN')
sheet1.write(0, 2, 'SHASTRADHARA')
sheet1.write(0, 3, 'CLEMEN TOWN')
sheet1.write(0, 4, 'RAJPUR ROAD')
sheet1.write(0, 5, 'CLOCK TOWER')


wb.save('Example3.xls')

Output

In this code, we are using the write function to write data in an excel sheet. After running the code, an excel sheet will be created with the following content:

Muskaan Chandan Risk Chirag Ayush
Rohan
Nikhil
Roshan
Mudit
Rahul 
Writing to Excel using Python

Formatting Excel

We can add some styles and format the cells of an excel sheet by adding multiple styles to it by using the xslx writer module. To do that, we just need to define our style and pass it to our write function as an argument.

importxlwt #importing module
fromxlwt import Workbook


wb = Workbook()


worksheet = wb.add_sheet('Sheet 1')




style =xlwt.easyxf('font: bold 1, color red;')
row = 0
column = 0


content = ["Roahn", "Nikhil", "Roshan", "Mehak", "Mudit", "Muskaan", "Chandan"]
for item in content :
worksheet.write(row, column, item,style)


column+=1


wb.save('Example4.xls')

Output

After running the code, you will get the following output

RohanNikhilRoshanMehakMuditMuskaanChandan
Writing to Excel using Python

Related Topics

Iterate a Dictionary in Python

In this tutorial, we will learn how to Iterate a Dictionary in Python. Dictionary: In Python, a dictionary is an unordered collection of data values that is used to store data values,...

3 minutes read.

Artificial intelligence mini projects with source code in Python

Project Name: Movie recommendation system A recommendation provides customers with relevant information related to their searches. Before the recommendation system, the most common method of purchasing was to rely on the...

4 minutes read.

How to plot multiple linear regression in Python

This article lets us look into linear regression in Python and how we can plot multiple linear regressions in it. Linear regression One of the simplest and most widely used Machine Learning...

4 minutes read.

Pillow Python introduction and setup

Introduction Advanced image processing implies handling the picture carefully with the assistance of a PC. Utilizing picture handling we can perform activities like upgrading the picture, obscuring the picture, separating text...

4 minutes read.

Comments in the Python Programming Language

In this tutorial, we will learn how to comment in multiple lines and paragraphs in the python programming language. Commenting a Paragraph in Python Most people think the importance of comments is...

2 minutes read.

Python String find() method

Python String find() method The string.find() method in Python finds the first occurrence of the specified value and returns the lowest index in the string if the substring sub is found else it...

2 minutes read.

List Index out of Range Python for Loop

The List is generally used in Python to store multiple items or elements inside one single variable. The List is ordered in nature, the List can contain the elements inside...

3 minutes read.

Python Errors and exceptions

Exceptions and errors are the obstacles a programmer constantly faces while writing a program. Firstly, we need to understand what are errors and exceptions and the difference between these two...

6 minutes read.

Insertion Sort using Python

Insertion sort is a type of sorting technique that is used for sorting an array with random elements. Using sorting methods, any unsorted array can be sorted into ascending or...

3 minutes read.

Python Infinity

Introduction We will discover how to define an infinite number in Python in this tutorial. Infinity, as we all know, is a value that cannot be defined and can either be...

5 minutes read.

Sys Module in Python

What are Modules? The Modules are the kind of files that contain Python statements and definitions. The module is known by the name of the file followed by the suffix “.py”....

5 minutes read.

Isreal() Python

Python Programming Language Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

4 minutes read.

Write Text files in Python

Let's discuss writing the text file in detail. Generally, writing text also follows the same procedure as like reading text. It varies only in some specific places. Steps followed for writing...

4 minutes read.

Python Tuple index() Method

Python Tuple index() Method The tuple.index() method of Python finds the first occurrence of the specified value and returns its index if the value is found else raises an exception if...

1 minute read.

Python SciPy Library

Introduction SciPy, a logical library for Python is an open-source, BSD-authorized library for arithmetic, science, and design. The SciPy library relies upon NumPy, which gives advantageous and quick N-dimensional exhibit control....

6 minutes read.

Word frequency Python

Word frequency Python In this tutorial, we will write the Python program to count the occurrence of a word (word frequency) in a given sentence. We will learn all the approaches...

5 minutes read.

Iterate a Dictionary in Python – Part 2

In this tutorial, we will learn above various methods used to Iterate a Dictionary in Python. Dictionary: In Python, a dictionary is an unordered collection of data values that is used to...

3 minutes read.

Python Dictionary fromkeys() method

Python Dictionary fromkeys() method The dictionary.fromkeys() method in Python creates a new dictionary from the given sequence of elements and returns a dictionary with the specified keys and values. Syntax dictionary.fromkeys(sequence[, value]) Parameter sequence- This...

1 minute read.

Python String ljust() method

Python String ljust() method The string.ljust() method in Python will left align the string, where the padding is done using the parameter fillchar (space is default). Syntax String.ljust(width[, fillchar]) Parameter width: This parameter represents the...

2 minutes read.

Ternary operators in python

Starting from Python version 2.5, ternary operators are also known as Conditional operators. Using these operators, we can evaluate any problem based on a condition. It is an alternative and...

4 minutes read.