nicuf

excel-import

Jul 18th, 2021 (edited)
420
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.53 KB | None | 0 0
  1. ENGLISH: https://neculaifantanaru.com/en/how-to-import-data-from-one-excel-file-to-another-excel-file-with-python.html
  2. -------------------
  3.  
  4. import openpyxl #open the bookstore I want to work with
  5.  
  6. wb_AAA = openpyxl.load_workbook("AAA.xlsx") #open the file in which I import the data
  7. ws_1 = wb_AAA['Date_angajati'] #define the sheet I work with
  8.  
  9.  
  10. wb_UI = openpyxl.load_workbook("ttestui.xlsx") #open the file from which I import the data
  11. ws_2 = wb_UI['UI']
  12.  
  13. sh_obj = wb_UI.active
  14. max_row = sh_obj.max_row
  15. # loop will print all values
  16. # of column1, 2, 4, etc
  17.  
  18. code2name = {}
  19. for i in range(2, max_row+1):
  20.     cell_obj = sh_obj.cell(row=i, column = 4)
  21.     # print(cell_obj.value)  displays the data in column 4 wb testUI
  22.     code2name[sh_obj.cell(row=i, column=1).value]=(sh_obj.cell(row=i, column=4).value, sh_obj.cell(row=i, column=5).value) #associate the search value (vlookup excel) with the definitions in the testUI
  23. print(code2name)
  24.  
  25. for i in range (2, ws_1.max_row):
  26.     print(i)
  27.     """
  28.    associate the columns where I import data with the value by which I search for them (vlookup)
  29.    get is the equivalent of "iferror"
  30.    ('','') ...if iferror('value', ''), displays error, in the sense that it searches for the first character out of nothing
  31.    [0][1] refers to line 19, the values after =
  32.    """
  33.     ws_1.cell(row=i, column=7).value = code2name.get(ws_1.cell(row=i, column=6).value, ('',''))[0]
  34.     ws_1.cell(row=i, column=10).value = code2name.get(ws_1.cell(row=i, column=6).value, ('',''))[1]
  35. wb_AAA.save('BBB.xlsx')
Add Comment
Please, Sign In to add comment