In this post we will be creating a Python script that will write data to an Excel spreadsheet using the openpyxl library. Openpyxl is a library that allows us to interact with Excel files in Python. It provides a range of tools for reading, writing, manipulating, and formatting Excel data. This makes it a useful tool for data analysis and reporting tasks.
See the sample of Python code below where we use the openpyxl library to write data to a new Excel spreadsheet. We start by creating a new Excel file called
example.xlsx and assign it to a variable named
workbook. We then retrieve the active worksheet from the workbook, this is the worksheet displayed when the Excel file is opened. Next we set the values of cells in the worksheet. In this example we are adding data to cells individually. Finally the changes made to the Excel file are saved using the
import openpyxl workbook = openpyxl.Workbook() worksheet = workbook.active worksheet['A1'] = 'Name' worksheet['B1'] = 'Role' worksheet['A2'] = 'John' worksheet['B2'] = 'IT Support Engineer' worksheet['A3'] = 'Jane' worksheet['B3'] = 'Software Developer' workbook.save('example.xlsx')
See below a screenshot of what our resulting worksheet looks like.
Take a look at some of our other content around the Python programming language by clicking here.