Python - Validate if a sheet exists in my document xls

被刻印的时光 ゝ 提交于 2019-12-05 10:13:40
SparkAndShine

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.

PS: For older Microsoft Excel files (i.e., .xls), use xlrd and xlwt instead.

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')

Install openpyxl with the following command.

$ sudo pip install openpyxl

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
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!