Python Write Excel File
First, let’s create a new spreadsheet, and then we will write some data to the newly created file. An empty spreadsheet can be created using the Workbook() method. Let’s see the below example.
Example:
In this example, a new blank Excel workbook is generated using the openpyxl library’s Workbook()
function, and it is saved as “sample.xlsx” with the save()
method. This code demonstrates the fundamental steps for creating and saving an Excel file in Python.
Python3
from openpyxl import Workbook workbook = Workbook() workbook.save(filename = "sample.xlsx" ) |
Output:
After creating an empty file, let’s see how to add some data to it using Python. To add data first we need to select the active sheet and then using the cell() method we can select any particular cell by passing the row and column number as its parameter. We can also write using cell names. See the below example for a better understanding.
Example:
In this example, the openpyxl module is used to create a new Excel workbook and populate cells with values such as “Hello,” “World,” “Welcome,” and “Everyone.” The workbook is then saved as “sample.xlsx,” illustrating the process of writing data to specific cells and saving the changes
Python3
# import openpyxl module import openpyxl wb = openpyxl.Workbook() sheet = wb.active c1 = sheet.cell(row = 1 , column = 1 ) # writing values to cells c1.value = "Hello" c2 = sheet.cell(row = 1 , column = 2 ) c2.value = "World" c3 = sheet[ 'A2' ] c3.value = "Welcome" # B2 means column = 2 & row = 2. c4 = sheet[ 'B2' ] c4.value = "Everyone" wb.save( "sample.xlsx" ) |
Output:
Refer to the below article to get detailed information about writing to excel.
Working with Excel Spreadsheets in Python
You all must have worked with Excel at some time in your life and must have felt the need to automate some repetitive or tedious task. Don’t worry in this tutorial we are going to learn about how to work with Excel using Python, or automating Excel using Python. We will be covering this with the help of the Openpyxl module and will also see how to get Python in Excel.