Python - Validate if a sheet exists in my document xls
The Python library xlsxwriter offers a great interface to Excel with all the formatting & graphing functions you'd expect. The following code fragment checks if a worksheet exists, creates one if it doesn't, and returns the worksheet object:
import xlsxwriter
workbook = xlsxwriter.Workbook(workbook_file)
worksheet = workbook.get_worksheet_by_name(worksheetName)
if worksheet is None:
worksheet = workbook.add_worksheet(worksheetName)
Install xlsxwriter by the command:
sudo pip install xlsxwriter
The Python library openpyxl
is designed for reading and writing Excel xlsx/xlsm/xltx/xltm
files. The following snippet code checks if a specific sheet name exists in a given workbook.
from openpyxl import load_workbook
wb = load_workbook(file_workbook, read_only=True) # open an Excel file and return a workbook
if 'sheet1' in wb.sheetnames:
print('sheet1 exists')
PS: For older Microsoft Excel files (i.e., .xls
), use xlrd
and xlwt
instead.
Install openpyxl
with the following command.
$ sudo pip install openpyxl