Create and write on excel file using xlsxwriter module in Python

PythonServer Side ProgrammingProgramming

Python’s wide availability of libraries enables it to interact with Microsoft excel which is a very widely used data processing tool. In this article we will see how we can use the module named xlsxwriter to create and write into a excel file. It cannot write into existing excel file.

Writing to Each Cell

We can write to each cell of an excel sheet by writing to the name of the cell. In the below example we create a workbook and then ass a worksheet to it. Finally write to the cells of the worksheet using the write() method.

Example

import xlsxwriter

# Cretae a xlsx file
xlsx_File = xlsxwriter.Workbook('Schedule.xlsx')

# Add new worksheet
sheet_schedule = xlsx_File.add_worksheet()

# write into the worksheet
sheet_schedule.write('A1', 'Day')
sheet_schedule.write('A2', 'Mon')
sheet_schedule.write('A3', 'Tue')

sheet_schedule.write('B1', 'Schedule')
sheet_schedule.write('B2', 'Final Exam')
sheet_schedule.write('B3', 'party')

# Close the Excel file
xlsx_File.close()

Output

Running the above code gives us the following result −

Writing directly to Rows

In this approach we can initialize the row and column number from where we want to start writing. Then use a for loop to add required values to the rows and cells by dynamically increasing their values. In the below example we only add more rows. But by designing a loop within a loop we can also create both columns and rows dynamically.

Example

import xlsxwriter

# Cretae a xlsx file
xlsx_File = xlsxwriter.Workbook('Days.xlsx')

# Add new worksheet
sheet_days = xlsx_File.add_worksheet()

row = 1
column = 1

days = ['Mon','Tue','wed','Thu','Fri','Sat']

# Iterating through days list
for day in days:
sheet_days.write(row, column, day)
row += 1

# Close the Excel file
xlsx_File.close()

Output

Running the above code gives us the following result −

raja
Published on 26-Aug-2020 06:42:39
Advertisements