2017-09-14 1 views
0

누군가가 약간의 도움을 줄 수 있기를 바랍니다. 하나의 Excel 통합 문서에서 DownTime이라는 제목의 데이터를 가져 와서 코일이 경험 한 "코드"와 일치하는 코일 (제품) 숫자 사전을 만듭니다. 나는이 부분을 성취 할 수 있었으며, 꽤 똑바로 전진했다.한 엑셀 통합 문서에서 사전 만들기, 다른 통합 문서와 키 일치, 값 붙여 넣기

위로 올라가고있는 부분은 코일 번호를 다른 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 항목이 있습니다.

을 내가, 내가 통합 문서의 다운 타임 만든이 사전을 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을"일치와 "코드"로 값을 붙여 싶습니다.

내가 충분히 설명했으면 좋겠다. 코드에 대한 도움이나 참조 용 웹 사이트를 가리켜 주시면 대단히 감사하겠습니다. 나는이 모든 코드를 직접 입력하고 싶지 않습니다!

감사합니다.

답변

1

많은 연구와 시행 착오 끝에 우발적으로 파일을 손상시키고 일반적으로 비단뱀에 좌절감을 느껴서 알아 냈습니다.

# -*- 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() 

나는 이것이 아마이 코드의 짧은 버전이 아닙니다 그것은 내 선택의 엑셀 파일에 직접 붙여 갈 수있는 방법은 여러가지가 아마 거기 이해하지만, 내가 나오지 않았어 : 여기에 내가 무엇을 가지고 그 부분을 아직 풀지 못했습니다.

나는 다르게 pyexcel을 사용하고 있습니다. 이것은 값을 행이나 열에 붙여 넣기 만하면되는 가장 쉬운 방법입니다. join을 사용하여 생성 된 목록 목록을 깨고 각 하위 목록을 자체 행에 삽입 할 수있게했습니다. 나는 현재 생성 된 행을 다른 Excel 통합 문서에 저장하는 데 정착했는데, 이는이 탐색 중에 통합 문서가 지속적으로 손상 되었기 때문입니다. 그러나 원하는 통합 문서에 붙여 넣을 행을 복사해야하는 마지막 단계를 제거하기 위해이 코드를 조작하는 방법을 알고 있다면 알려주십시오.

관련 문제