Python - 验证我的文档 xls 中是否存在工作表 [英] Python - Validate if a sheet exists in my document xls

查看:54
本文介绍了Python - 验证我的文档 xls 中是否存在工作表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在空闲时间尝试设计一个小程序,它加载一个 xls 文件,然后在要扫描的文档中选择一张纸.

I am trying to design a small program on my free time which loads an xls file, then select a sheet in the document to be scanned.

步骤 1:用户导入 .xls 文件.导入后程序检查文件是否存在.(我能做到的)

Step 1: the user imports an .xls file . After importing the program checks whether the file exists. (That I can do )

第 2 步:我要求用户给出要分析的文档表 xls 的名称.这就是它停止的地方.程序没有检测到可用的工作表:(

Step 2: I ask the user to give the name of the document sheet xls to analyze. And that 's where it stops. the program does not detect the sheets available :(

#check if the document exist
while True:
    x = input("Give the name of the document in this repository__")
    input_filename = x + ".xls"
    if os.path.isfile(input_filename):
        print ("the document is been charged")
        break
    else:
        print("xls not found !")

#Load the document
xls_file = pd.ExcelFile(input_filename)

#Select the good sheet in file
print ("this is your sheets in this document",xls_file.sheet_names)
while True:
    feuilles = input("Select yout sheet")
    input_feuilles = feuilles
    if xls_file.sheet_names(input_filename):
        print ("The sheet is been charged !")
        break
    else:
        print("This sheet don't exist!")

我真的不知道如何验证用户填写的表单是否真的存在.

I really do not know how to verify that the sheet filled by the user really exists.

推荐答案

Python 库 openpyxl 专为读写 Excel xlsx/xlsm/xltx/xltm 文件而设计.以下片段代码检查给定工作簿中是否存在特定工作表名称.

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:对于较旧的 Microsoft Excel 文件(即 .xls),请改用 xlrdxlwt.

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

使用以下命令安装 openpyxl.

$ sudo pip install openpyxl

这篇关于Python - 验证我的文档 xls 中是否存在工作表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆