简体   繁体   English

检查Excel工作表是否为空

[英]Check if a Excel Sheet is empty

I have an excel workbook with multiple sheets. 我有一本具有多个工作表的Excel工作簿。 I need to delete the sheets which are completely empty, as my code when processing finds a blank sheet it fails. 我需要删除完全为空的工作表,因为我的代码在处理过程中发现一张空白工作失败。

os.chdir(path)
list_file=[]
for file in glob.glob("*.xlsx"):
    print(file)
    list_file.append(file)

I have listed all the files here available. 我列出了所有可用的文件。

AB_list=[s for s in list_file if "India" in s]
CD_list=[s for s in list_file if "Japan" in s]

Then, i store the file names is list as per requirement. 然后,我存储文件名是按要求列出的。 Now I need to delete empty sheets from those excel files before I move them to a dataframe. 现在,我需要先从这些excel文件中删除空白表,然后再将其移至数据框。 Then loop through to read the files into individual dataframe. 然后循环遍历以将文件读入单个数据帧。

You've tagged openpyxl so I assume you're using that. 您已经标记了openpyxl所以我认为您正在使用它。

# workbook is opened MS Exel sheet opened with openpyxl.Workbook
empty_sheets = []
for name in workbook.get_sheet_names():
    sheet = workbook.get_sheet_by_name(name)
    if not sheet.columns():
        empty_sheets.append(sheet)

map(workbook.remove, empty_sheets)

ws.max_row and ws.max_column should give you last used cell position. ws.max_rowws.max_column应该给您上次使用的单元格位置。 Based on that you can determine if sheet is empty. 基于此,您可以确定工作表是否为空。 Also check if this works for you ws.calculate_dimension() , which should return a range. 另外,请检查ws.calculate_dimension()是否适合您,该方法应该返回一个范围。

All the functions are from openpyxl which you are already familiar with. 所有功能都来自您已经熟悉的openpyxl

you can easily do this with pandas which I'm using too. 您也可以使用我也在使用的熊猫轻松做到这一点。 here 这里

and code looks like 和代码看起来像

import pandas as pd

df = pd.read_csv(filename) # or df = pd.read_csv(filename) #或

pd.read_excel(filename) for xls file df.empty xls文件df.empty的pd.read_excel(filename)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM