如何在排除数组中的某些行的同时迭代另一个工作表来创建工作表的副本。

问题描述 投票:1回答:1

我正在使用Openpyxl比较两个工作簿我将它递增一个计数器供以后使用,然后跟踪应该从初始工作簿中删除的行。如何从该工作簿中删除这些行或创建新工作表(将原始文件删除)或删除这些行的工作簿?

我已经编写了代码,直到这一点,但我没有找到很多在写入或删除工作簿中的行,我没有任何具体的运气,有人建议我创建一个工作簿的副本,但我也这样做没有成功。

from openpyxl import load_workbook
from tkinter import Tk
from tkinter.filedialog import askopenfilename
import datetime
import time

class ManualReporter:
    def __init__(self):
        '''
        Initializes Variables for use within the Class
        Hides the tkinter pop-up when using the file dialog
        '''
        Tk().withdraw()
        self.sap_file = None
        self.tracker_file = None
        self.wb_sap = None
        self.wb_wt = None
        self.XT = 0
        self.deadrows = []


    def open_sapfile(self):
        '''
        Sets the sap_file variable to be the first  directory to the SAP Report based on what the User Selects in the File Dialog
        Sets that directory and the file as the current workbook under the variable self.wb_sap
        Creates a Backup of the SAP Report so that if Errors Occur a Fresh Clean Copy is Present
        '''
        self.sap_file = askopenfilename()
        self.wb_sap = load_workbook(filename=self.sap_file)
        # Code to create a backup File in-case of Error or Fault
        copyfile = "Untimed_Report_SAP_" + str(datetime.date.today())+".xlsx"
        self.wb_sap.save(copyfile)
        print(self.sap_file)
    def open_tracker(self):
        '''
        Same as Above, sets self.tracker_file as a filedialog which retrieves the file's directory (User Inputted)
        Loads the File Workbook as self.wb_wt
        Creates a Backup of the Second SAP Report so that if Error Occurs a Clean Copy is Present.
        '''
        self.tracker_file = askopenfilename()
        self.wb_wt = load_workbook(filename=self.tracker_file)
        print(self.tracker_file)
    def check_rows(self):
        '''
        Sets the Active Sheets in Both the Workbook Variables,
        Creates a New Sheet in the Newest Report to Contain the Modified Data,
        Iterates through the Rows of the Two Sheets checking for a Comparison in Part Number,
        OpCode and then Compares the X/T/P Classification and Adjusts Data in Second Sheet
        '''
        start = time.time()
        sap = self.wb_sap.worksheets[0] #Sets The First Sheet in the Excel Workbook as the variable sap
        wt = self.wb_wt.worksheets[0]#Sets the First Sheet in the Second Report as the var wt
        ws1 = self.wb_sap.create_sheet("Sheet1", 1)#Create a Spare Sheet in the First Report to place the Adjusted Data
        ws1 = self.wb_sap.worksheets[1]#Sets ws1 as the Active Second Sheet for New Data
        for saprow in sap.iter_rows():
            for wtrow in wt.iter_rows():
                if (saprow[3].value == wtrow[4].value and int(saprow[2].value) == int(wtrow[5].value)):#  IF Material NUM & OPCode MATCH DO:
                    if wtrow[7].value in ("T","P"): #WT Entry is Marked as T/P
                        if saprow[4].value is "X": #SAP Report Entry is Marked as X
                            self.XT += 1#Increment X->Ts Counts
                            #print("X->T")
                            self.deadrows.append(saprow)
                        else:
                            if saprow not in self.deadrows:
                                ws1.append(saprow)


        end = time.time()
        #print("Finished, Total X->Ts: ", self.XT)
        print("Time Taken: ", (end - start))



x = ManualReporter()
x.open_sapfile()
x.open_tracker()
x.check_rows()

我的期望是输出将是工作簿的精确副本,但是从该工作簿中删除了具有某些值更改的行。我希望能够删除它们,但除了破坏的代码或问题之外,我所做的任何方法都没有实现。

                    self.deadrows.append(saprow)
                else:
                    if saprow not in self.deadrows:
                        for i in saprow:
                            #Code to Create a row in ws1.
                            #Code to Append value of saprow[i] to current ws1 rows

编辑1:我包括我的尝试将行附加到复制的工作表。编辑2:我虽然手动迭代Saprow并将数据附加到新工作表的行中,但我已经难以理解它。

python openpyxl
1个回答
1
投票

在大量帮助之后,我得出的结论是,要将数据从一个工作表复制到另一个工作表,您可以通过此方法逐行复制数据:

self.workbook = load_workbook(filename="filepath")
sheet1 = self.workbook.worksheet[0]
sheet2 = self.workbook.create_sheet("Sheet 2")
sheet2 = self.workbook.worksheets[1]
for row in sheet1.iter_rows():
    sheet2.append([cell.value for cell in row])

我还想知道你是否想要过滤掉你可以添加的数据,如果上面的for循环中的语句可以限制哪些行将其单元格写入新工作表。

self.RowsToExclude = Some List containing row data that will be excluded.
for row in sheet1.iter_rows():
    if row not in self.RowsToExclude:
        ws1.append([cell.value for cell in row])

最后,我要感谢所有为我做出贡献的人。

© www.soinside.com 2019 - 2024. All rights reserved.