从一个Excel工作簿创建字典,将键与另一个工作簿匹配,粘贴值

时间:2017-09-14 20:46:16

标签: python-3.x

我希望有人可以提供一些帮助。我试图从一个名为DownTime的excel工作簿中提取数据,并创建一个与"代码"匹配的线圈(产品)编号字典。那个线圈经历过。我已经能够完成这一部分,它非常直接。

绊倒我的部分是如何将线圈编号与不同的excel工作簿匹配,并粘贴相应的"代码"。

所以这就是我到目前为止:

import openpyxl
from collections import defaultdict

DT = openpyxl.load_workbook('DownTime.xlsm')
bl2 = DT.get_sheet_by_name('BL2')
CS = openpyxl.load_workbook('CoilSummary.xlsm')
line = CS.get_sheet_by_name('BL2')
#opening needed workbooks with specific worksheets


coil =[]
rc = []
code = defaultdict(set)
cnum = ''
next_row = 2
col = 32

for row in range(2, bl2.max_row + 1):
    coil = bl2['K' + str(row)].value
    rc = bl2['D' + str(row)].value
    code[coil].add(rc)
    # Creating a dictionary that represents each coil with corresponding codes

for key,value in code.items():   
    cnum = line['B' + str(row)].value
    if cnum == key:
        line.write(next_row, col, value)
        next_row+=1
# Attempting to match coil numbers with dictionary and column B
# if the key is present, paste the value in column AF    

CS.close()
DT.close() 

字典的示例输出如下所示:

('M30434269': {106, 107, 173}, 'M30434270': {132, 424, 106, 173, 188}, 'M30434271': {194, 426, 202, 106, 173}})

只有大约22,000个条目。

重申我想要完成的事情:

我想从工作簿DownTime中获取这个字典,将字符串与CoilSummary中的列匹配,如果键与单元格条目匹配,则将值粘贴到表格末尾的空白单元格中。

示例:

"CoilNum"      "Date"         "Shift"  "info1" "info2"  "Code"
M30322386   03/03/2017 06:48:30  3       1052     1722   '    '
M30322390   03/03/2017 05:18:26  3       703      1662   '    '

我想匹配" CoilNum"使用字典中的键,将值粘贴到" Code"。

我希望我解释得那么好。任何有关代码的帮助,或指向网站以供参考,将非常感谢。我只是不想手动输入所有这些代码!

谢谢!

1 个答案:

答案 0 :(得分:1)

经过大量的研究和反复试验,不小心破坏了excel文件并且普遍对python和excel感到沮丧,我想通了。这就是我所拥有的:

# -*- coding: utf-8 -*-

# importing tools needed for the code to work
import pyexcel as pe
from collections import defaultdict
import openpyxl as op


coil =''
rc = {}
code = defaultdict(list)
next_row = 2
col = 33
cnum = []
temp = ''



def write_data(code,cnum):
    ''' Used to open a given sheet in a workbook. The code will then compare values 
collected from one column in a specific sheet referred to as "coils" and compares it to a dictionary where the key's are also "coils."
    If the coil number matches, the code will then paste the values in a new workbook. From here the values can be copied by hand and pasted into the excel file of choice.'''
    sheet = pe.get_sheet(file_name="CoilSummaryTesting.xlsx")
    next_row = 2
    lst = []

    while next_row <= len(cnum):
        for key in code.keys(): 
            for step in cnum: 
                if str(step) == str(key):
                    for val in code.values():
                        temp = val
                        lst.append(temp)
                        next_row+=1  


                if step!=key:
                    break
        break

    for item in lst:
        sublist = (" ").join(str(item))
        sheet.row+= [sublist]
    sheet.save_as("CoilSummaryTest.xlsx")
    print("\nCoils Compared: ",next_row)            



def open_downtime():
    ''' Pull data from a second excel file to obtain the coil numbers with corresponding downtime codes'''

    DT = op.load_workbook('DownTime.xlsm')
    bl2 = DT.get_sheet_by_name('BL2')
    n = 1

    for row in bl2.iter_cols(min_col=11,max_col=11):
        for colD in row:
            code[colD.offset(row=1,column=0).value].append(colD.offset(row=1,column=-7).value
        n+=1
    print('\nNumber of rows in DownTime file: ',n)  
    return code

def open_coil():
    '''Opens the first workbook and sheet to know how many rows are needed for coil comparision.'''

    i = 1
    CSR = op.load_workbook('CoilSummaryTesting.xlsx')
    line_read = CSR.get_sheet_by_name('BL2')


    for rows in line_read.iter_cols(min_col=2, max_col=2):
      for col in rows:

            cnum.append(col.offset(row=1,column=0).value)
            i+=1

    print('\nNumber of rows in CoilSummary file: ',i)    



    return write_data(open_downtime(),cnum)


def main():
    sheet = open_coil()



if __name__ == "__main__":
     main()

我知道这可能不是这段代码的最短版本,并且可能有很多方法可以将它直接粘贴到我选择的excel文件中,但我还无法解决这个问题。

我做的不同之处在于使用pyexcel。当将值粘贴到行或列中时,这被证明是最简单的。使用join,我打破了生成的列表列表,允许每个子列表插入到自己的行中。我目前决定将生成的行保存到不同的excel工作簿,因为在此探索期间不断损坏工作簿;但是,如果有人知道如何操作此代码以消除必须复制行以粘贴到所需工作簿的最后一步,请告诉我。