×

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

Convert int to Float in Python using Pandas

Introduction We have already learnt about how to convert float variables to int. Now let us know how to convert int variables to float So let us create another Dataset on which...

2 minutes read.

How to check the version of the Python Interpreter?

As we all know what an interpreter is, and how important it is. We should also be aware of the fact that it is important to have knowledge of the...

2 minutes read.

Python List append() Method

Python List append() Method The list.append() method in Python adds or appends an item to the end of the list. Syntax list.append(x) Parameter x: It is a required parameter that represents an element of any type (string, number,...

1 minute read.

Yield vs Return in Python

In this article, you will learn about " Yield " and " Return " in Python. You will also understand the difference between " Yield " and " Return "...

6 minutes read.

Gethostbyname() function in 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...

6 minutes read.

Hypothesis Testing in Python

Hypothesis Testing in python is widely used along with statistics. Many libraries in Python are very useful for statistics and machine learning. Libraries like numpy, scripy etc. help in hypothesis testing in...

12 minutes read.

Python Euclidean Distance

Euclidean distance is the distance between two points with whatever of dimensions. We are using NumPy library to find and calculate the Euclidean distance. The NumPy library is used for...

1 minute read.

Python MySQL Database Connection

In this article, you will be able to understand how to connect to a MySQL database through Python. We generally can use many methods or modules to connect to the database...

6 minutes read.

Python String Lowercase

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....

3 minutes read.

Python random.seed() function

The random module in Python produces a random number or pseudo-random data, that is, deterministic. The seed function records the state of a random function to provide the same random...

6 minutes read.

Create the First GUI Application using PyQt5 in Python

GUI: A graphical user interface, or GUI, is present on most personal computers. It provides a simple experience for individuals with various computing skill levels. GUI apps may take more resources...

3 minutes read.

os.stat() method in Python

In Python, the os module provides the capacity to interact with the operating system. The operating system comes under the Python module. In this module, Python provides a specific feature...

3 minutes read.

Traverse Dictionary in Python

Traversing a dictionary is visiting each and every step in the dictionary, which is also called iterating the dictionary In Python, dictionaries are a useful and commonly used data structure in...

3 minutes read.

Continue and Pass Statements in Python

Difference between continue and pass statements in Python The tasks can be repeated and automated efficiently using loops in Python. Sometimes we have to exit from the entire loop completely, we...

2 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.

Python Validator

Validator  The validator is a library available in the python programming language. The library in python consists of all the related modules which can be imported to perform the required operation....

3 minutes read.

Python Constructor

Introduction A constructor is defined as the special kind of function or method that is used for instance variables initialization during the creation of an object of a class. The constructor's task...

5 minutes read.

JWT Decode Python

Python's PyJWT package makes it possible to encrypt and decrypt JSON Web Tokens (JWT). JWT is a public, recognized global benchmark for safely expressing demands between two parties (RFC 7519). JSON...

7 minutes read.

Wikipedia module in Python

Wikipedia module in Python: The internet has become an essential part of all of our life which is the largest source of all the information. Therefore, it becomes very important...

7 minutes read.

Division in Python

In this tutorial, we will understand what mathematical operation division is and how is it performed in Python Programming language. We will also focus on the operators being used in...

3 minutes read.