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

时间:2019-03-27 21:15:36

标签: python openpyxl

我正在使用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并将数据追加到新工作表的行中,但我很烦恼自己。

1 个答案:

答案 0 :(得分: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循环内添加if语句,以限制将哪些行的单元格写入新工作表中。

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])

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