×

Python Write Excel File

Python Write Excel File

The Python xlwt module is used to write an excel file and perform multiple operations on it. It can be used to write text, numbers, and formulas for multiple worksheets. It also supports a feature like formatting, images. Chart, page setup, auto filters, and many others.

Python does not come with the xlwt module; we need to install it using the pip from the command line.

pip install xlswriter

Writing excel file openpyxl module

It is defined as a package which is commonly suggested if you want to read and write .xlsx, xlsm, xltx, and xltm files. You can check it by running type(wb).

The Python provides the load_workbook () function which takes an argument and returns a workbook object, which denotes the file. It should be remembered that you are in the same directory where your spreadsheet is located. Otherwise, the Python interpreter will show an error.

We can easily use for loop with the help of the range() function to help print out the values of the rows that have values in column 2. If those specific cells are empty, we will get none.

import openpyxl
# Workbook() function of openpyxl is used to  
# create a new blank Workbook object
wb = openpyxl.Workbook()
# Get workbook active sheet
# from the active attribute
sheet = wb.active
 # Cell object is created by
# using sheet object's cell() method.
c1 = sheet.cell(row=1, column=1)
# writing values to cells
c1.value = "HIMANSHU"
c2 = sheet.cell(row=1, column=2)
c2.value = "DUBEY"
# Once have a Worksheet object, one can
# access a cell object by its name also.
# A2 is denoted column = 1 & row = 2.
c3 = sheet['A2']
c3.value = "RAHUL"
# B2 is denoted column = 2 & row = 2.
c4 = sheet['B2']
c4.value = "TRIVEDI"
c5 = sheet['A2']
c5.value = "RAHUL"
# B2 is denoted column = 2 & row = 2.
c6 = sheet['B2']
c6.value = "TRIVEDI"
# Anytime we modify the Workbook object
# the file will not be saved until you call
# the save() workbook method.
wb.save("C:\\Users\\DEVANSH SHARMA\\Desktop\\demo.xlsx") 

Output:

We will get the following file

 

Writing excel file openpyxl module

Writing data to Excel file with xlwt

We can use the xlwt package, instead of the XlsxWriter package to create the spreadsheets that contain the data. It is an another package for writing data, formatting information, etc. and suitable for writing the data and format information to files with .xls extension. It can perform multiple operations on the spreadsheet.

It allows performing operations such as formatting, images, charts, page setup, auto filters, conditional formatting, and many others.

The Python library pandas provide excellent methods for reading all kinds of data from excel files. We can also import the results back to pandas.

Consider the following program

import xlwt
from xlwt import Workbook
# Workbook is created
wb = Workbook() 
# add_sheet is used to create sheet.
sheet1 = wb.add_sheet('Sheet 1')
 sheet1.write(1, 0, 'ANAND VIHAR')
 sheet1.write(2, 0, 'LAXMI NAGAR')
 sheet1.write(3, 0, 'SARITA VIHAR')
 sheet1.write(4, 0, 'LODHI GARDEN')
 sheet1.write(5, 0, 'SONIYA VIHAR')
 sheet1.write(6, 0, 'PITAMPURA')
 sheet1.write(7, 0, 'YAMUNA BANK')
 sheet1.write(8, 0, 'RAJIV CHAWK')
 wb.save('xlwt Address1.xls') 

Output:

We will get the excel file named Address1.xls

Writing data to Excel file with xlwt

Writing data to Excel file with pyexcel

We can easily export arrays back to a spreadsheet by using the save_as() function and by passing the name of the destination file to the dest_file_name argument.

It allows us to specify the delimiter and add dest_delimiter argument. You can pass the symbol that you want to use as a delimiter in-between " ".

import pyexcel
# make sure you had pyexcel installed
a_list_of_dictionaries = [
     {
         "Name": 'Adam',
         "Age": 28
     },
     {
         "Name": 'Beatrice',
         "Age": 29
     },
     {
         "Name": 'Ceri',
         "Age": 30
     },
     {
         "Name": 'Dean',
         "Age": 26
    } ]
pyexcel.save_as(records=a_list_of_dictionaries, dest_file_name="Book1.xls")

Related Topics

Count Number of Keys in Dictionary Python

Dictionary is a particular data type in python. Dictionary stores unique values by taking different keys and their assigned values. Through this article, we will learn about python dictionary count,...

3 minutes read.

Composition in Python

Composition in Python Composition is one of the important concepts of Object-oriented programming (OOPs). Composition basically enables us for creating complex types objects by combining other types of objects in the...

6 minutes read.

Yield Statement In Python

The generators are defined by using the yield statement in Python. Generally, it converts a normal Python function into a generator.  The yield statement hauls the function and returns back the...

2 minutes read.

Python String lower() method

Python String lower() method The string.lower() method in Python returns a string where all characters are lower case. Syntax string.lower() Parameter NA Return This method returns a string where all characters are lower case. Example 1 # Python...

1 minute read.

Python Pickle

The pickle is a module that enables serialization and de-serialization of the structure of the object in python. Pickling is the process that uses the protocols to convert the Python...

5 minutes read.

Python String isspace() method

Python String isspace() method The string.isspace() method returns a Boolean value true if there are only whitespace characters in the given string. This function is used to check if the given...

2 minutes read.

How to clear screen in Python?

How to clear screen in python There are times when we execute our program and it results in an unexpected output. The obtained result can contain some kind of garbage values...

4 minutes read.

Pointers in Python

In this tutorial, we will study what pointers are and if they have any utility in python. Now, let us understand what pointers are Pointers Pointers are special variables used to store the...

3 minutes read.

Difference between Input() and raw_input() functions in Python

There are two input functions in Python that are used for taking input are given below: raw_input()input() What is raw_input() Function? raw_input() function is a built-in function in Python. It is used to...

6 minutes read.

File Explorer using Tkinter in Python

File Explorer: Users can control folders and files on a device using an application known as a file manager or file explorer. Customers can access, edit, copy, delete, and start moving files...

3 minutes read.

Python Selectors

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

4 minutes read.

Collections in python

In this tutorial, we will see what is collection in python.  Further, we will see in-depth the different kinds of collections in python. Collections Collections in python are the built-in module used...

9 minutes read.

Front end in python

Python : Python is an object oriented programming language which is highly interpreted and is highly interactive. Python was created by Guido van Rossum in the year 1985 – 1990 .The...

4 minutes read.

Imread Python

In this walkthrough, we'll go over the specifics of using the imread() method of OpenCV-Python and various methods for loading images. Imread is an Image reading library. One of the most helpful...

7 minutes read.

One Liner If-Else Statements in Python

Before learning one liner if else Python, let us first know what Python is. Python is a broadly helpful, object-oriented and dependable language having a large number of utilizations from...

4 minutes read.

Python Parse Text File

We will learn different ways of read text records in Python. TL;DR The accompanying tells the best way to read all texts from the readme.txt document into a string: with open('readme.txt') as f: lines...

5 minutes read.

Creating Web Application in python

Web Application :  Web Application is an application software that runs in web browser . Software programs will run on operating system. Whereas Web Applications will run on World Wide Web...

5 minutes read.

Python NewLine

In python, a new line character denoted by "\n" is known as an escape character or escape sequence, and it will force the cursor to change its position to the next...

6 minutes read.

What does the if __name__ == "__main__" do in Python

In this article, you will learn about the If__name__==__main__ is a statement in python to define modules and the names of the modules. This statement plays a vital role in...

3 minutes read.

Sort Dictionary in Python

Dictionaries In Python, a dictionary is an unordered collection or set of data types that enable of store data in an unordered key-value/pair. The key is stored alongside with value. Dictionary contains key:...

4 minutes read.