首页 文章

条件检查工作表范围python

提问于
浏览
0

我有一个程序,可以解析多个工作簿中包含多个工作表的数据 .

第2至9页是一周中的几天(周日至周六) . 但是,某些纸张具有不同的纸张范围 .

有些床单有2到5个(周一至周五) . 其他一切都是一样的,只有一些工作簿总共有10张,而其他有8张 . 我的代码将对单元格范围进行相同的解析 .

如何仍然使用我的代码来解析具有工作表范围(2,5)的工作簿?这就是我到目前为止所拥有的 .

import glob
import openpyxl

path = 'C:/SomeFolder/*.xlsx'
files = glob.glob(path)
for file in files:
wb = openpyxl.load_workbook(file, data_only=True)
NameFile = file.rsplit('~', 2)[0]
sheet = wb.get_sheet_by_name('Title')
sheet2 = wb.get_sheet_by_name('TOTAL')
Week = sheet.cell(row=1, column=1).value
Date = sheet.cell(row=2, column=1).value
Name = sheet.cell(row=4, column=2).value
Title = sheet.cell(row=5, column=2).value
Site = sheet.cell(row=6, column=2).value
LocID = sheet.cell(row=7, column=2).value
Total = sheet2.cell(row=26, column=2).value
if wb.worksheets is range(2, 9):
    for n in range(2, 9):
        sheets = wb.worksheets[n]
        Days = wb.sheetnames[n]
        comment = sheets.cell(row=34, column=5).value
        for i in range(2, 57):
            From = sheets.cell(row=i, column=1).value
            To = sheets.cell(row=i, column=2).value
            Activity = sheets.cell(row=i, column=3).value
            TimeSheet = {'Sender': NameFile, 'Week': Week, 'Date': Date, 'Name': Name, 'Title': Title, 'Site': Site, 'LocID': LocID,
                        'Days': Days, 'From': From, 'To': To, 'Activity': Activity, 'Week Total': Total, 'Comments': comment}
else:
    for n in range(2, 5):
        for n in range(2, 9):
            sheets = wb.worksheets[n]
            Days = wb.sheetnames[n]
            comment = sheets.cell(row=34, column=5).value
            for i in range(2, 57):
                From = sheets.cell(row=i, column=1).value
                To = sheets.cell(row=i, column=2).value
                Activity = sheets.cell(row=i, column=3).value
                TimeSheet = {'Sender': NameFile, 'Week': Week, 'Date': Date, 'Name': Name, 'Title': Title,
                             'Site': Site, 'LocID': LocID,
                             'Days': Days, 'From': From, 'To': To, 'Activity': Activity, 'Week Total': Total,
                             'Comments': comment}
print(TimeSheet)

1 回答

  • 0

    您实际上可以按如下方式遍历工作表:

    for sheet in wb:
        if sheet.title=='Title':
            #Skip the title page with continue or do something to it here
            continue
        else:
            #for all pages other than the title page
            for i in range(2, 57):
                 From = sheet.cell(i, column=1).value
                 To= sheet.cell(i, column=2).value
    

    请注意我如何使用if语句跳过Title表 . 您可以通过这种方式跳过其他特定工作表 .

相关问题