Excel is a widely used spreadsheet application that allows users to organize, analyze, and visualize data. Python, a powerful programming language, provides various libraries for interacting with Excel files, and one such library is Openpyxl. In this article, we will explore how to leverage Openpyxl to automate Excel tasks, such as creating new workbooks and manipulating data.
1) Installing Openpyxl:
To get started, we need to install the Openpyxl library. Open your terminal or command prompt and run the following command:
pip install openpyxl
2) Creating a New Workbook:
Once Openpyxl is installed, we can begin by creating a new Excel workbook. Code for the same given below:
# import the required module import openpyxl # Create a new workbook object workbook = openpyxl.Workbook() # Get the active sheet object # bydefault 1st sheet sheet = workbook.active # Add data to the respective cells sheet['A1'] = 'Hello' sheet['B1'] = 'Biochemithon' # Save the workbook # in the given location path = r"C:\Users\hp\OneDrive\Documents\biochemithon_inp_out\biochemithon_example.xlsx" workbook.save(path)
This code creates a new workbook, adds data to cells A1 and B1, and saves the workbook as “biochemithon_example.xlsx”.
3) Reading Data from an Excel File:
Openpyxl allows us to read data from existing Excel files. We can extract information from specific cells, entire rows, or columns. Code for the same given below:
# import the required module import openpyxl path = r"C:\Users\hp\OneDrive\Documents\biochemithon_inp_out\biochemithon_example.xlsx" # Create a new workbook object # by Load an existing workbook workbook = openpyxl.load_workbook(path) # Get the active sheet object # bydefault 1st sheet sheet = workbook.active # Read data from respective cell cell_value = sheet['A1'].value print(cell_value)
In this snippet, we load the existing “biochemithon_example.xlsx” workbook, retrieve the active sheet, and extract the value from cell A1 then printed the value on the console.
4) Modifying Existing Data:
Openpyxl enables us to modify existing data within an Excel file. We can update values, apply formatting, or even add formulas. Code for the same given below:
# import the required module import openpyxl path = r"C:\Users\hp\OneDrive\Documents\biochemithon_inp_out\biochemithon_example.xlsx" # Create a new workbook object # by Load an existing workbook workbook = openpyxl.load_workbook(path) # Get the active sheet object # bydefault 1st sheet sheet = workbook.active # update data for respective cell sheet['A1'] = 'Updated Value' # Save the workbook # in the given location workbook.save(path)
In this code, we open the “biochemithon_example.xlsx” workbook, modify the value in cell A1 to “Updated Value”, and save the changes back to the file.
Conclusion:
Openpyxl is a powerful Python library that allows us to automate Excel tasks. Whether you need to create new workbooks, read and modify data, or work with multiple