簡體   English   中英

根據一系列值搜索和刪除Excel行

[英]Search for and delete Excel rows based on a range of values

我有兩個Excel文件,一個包含需要刪除的人員電子郵件列表(即刪除文件),另一個包含活動人員列表的Excel文件(即名冊文件)。 我想在花名冊文件的電子郵件列中搜索要刪除的電子郵件列表,然后將減去已刪除人員的新列表復制到新文件中。

我正在尋找使用Python實現的目標。 到目前為止,我的代碼如下:

from xlrd import open_workbook
import openpyxl

# Open Removal file
book1 = open_workbook('C:\Python27\Delete\Removals.xlsx')
sheet1 = book1.sheet_by_index(0)
search_remove_col = 0

# Open All Candidates file
book2 = open_workbook('C:\Python27\Delete\All Candidates.xlsx')
sheet2 = book2.sheet_by_index(0)
search_worker_col = 4

wb3 = openpyxl.load_workbook('c:\python27\delete\All Candidates.xlsx')
oldlivesheet = wb3.get_sheet_by_name('Live')

# Create a New Roster file
book3 = openpyxl.Workbook()
book3.save('c:\python27\delete\New Roster.xlsx')
book3 = open_workbook('C:\Python27\Delete\New Roster.xlsx')
sheet3 = book3.sheet_by_index(0)
new_worker_col = 4

# Interate through file, looking for worker to remove
for row_sheet1 in range(1, sheet1.nrows):

    workername = sheet1.cell(row_sheet1, search_remove_col).value

    for row_sheet2 in range(1, sheet2.nrows):                
            if sheet2.cell(row_sheet2,search_worker_col).value != workername:
                    sheet3.cell(row_sheet2,new_worker_col).value = sheet2.cell(row_sheet2,search_worker_col).value
                    print row_sheet2
            else:
                    print 'Worker to remove was found!'

book3.save('c:\python27\delete\New Roster.xlsx')

我遇到的問題是:

sheet3.cell(row_sheet2,new_worker_col).value = sheet2.cell(row_sheet2,search_worker_col).value

這將引發索引超出范圍錯誤。 我需要此行代碼將工作人員名稱復制到New Roster文件中的單元格中。

以下方法應該起作用。 首先將所有刪除內容加載到Python set 然后,它將遍歷All Candidates.xlsx文件中的條目,如果在刪除集中找到刪除列,則不會將其寫入新文件:

from xlrd import open_workbook
import openpyxl

# Open Removal file and create a set of required removals
book_removals = open_workbook(r'removals.xlsx')
sheet_removals = book_removals.sheet_by_index(0)
search_remove_col = 0
removals = set(sheet_removals.col_values(search_remove_col))

# Open the All Candidates file
book_candidates = open_workbook(r'All Candidates.xlsx')
sheet_candidates = book_candidates.sheet_by_index(0)
search_worker_col = 4

# Create a New Roster file
book_new = openpyxl.Workbook()
sheet_new = book_new.create_sheet(0)

# Iterate through candidates file, looking for removals
for row in range(sheet_candidates.nrows):
    if sheet_candidates.cell(row, search_worker_col).value not in removals:
        sheet_new.append(sheet_candidates.row_values(row))

book_new.save(r'New Roster.xlsx')

請注意,使用r'c:\\xxxxxxxxx\\xxxxxxxxx.xlsx'作為文件名,以避免使用反斜杠出現問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM