How to close workbook in Python using Openpyxl
In this tutorial, I will show you how to close workbook in Python using openpyxl. It’s easier than you think.
We have to use wb.close()
to close workook in openpyxl. Let’s see an example to understand how it works.
You can check: How to install openpyxl in Python
Importing Openpyxl
Make sure that Openpyxl is already installed in your system. You can import Openpyxl easily using the following commands.
from openpyxl.workbook import Workbook from openpyxl import load_workbook
- The first line of code imports the Workbook class from
openpyxl.workbook
module. Think ofopenpyxl.workbook
as a container containing Workbook class. A workbook class creates the worksheet. - The second line brings in the
load_workbook
function from the openpyxl module for efficient Excel file manipulation.
Load Existing Spreadsheet
Enlightenerwb = load_workbook('file.xlsx')
Here, the web stands for workbook and it is loading the workbook with the file path. Keep in mind, specifying the correct file path is essential for proper file access and manipulation.
The Python openpyxl
function loads the .xlxs file into the variable called wb.
Closing the workbook
After performing all the necessary work in the workbook, we need to close it. This command saves the changes made in the file. It is important mostly in larger datasets. In those, the changes are there in loops so it is important to do the same.
Save the Workbook
wb.save('file.xlsx') #This command will save the file with the changes.
Closing the Workbook
This command will close the workbook you were working on. It will also change the necessary changes made in the file.
wb.close()
Leave a Reply