2017-02-23 567 views
2

我需要遍歷一堆excel工作簿,並從每個工作簿中獲取一個值並將該值粘貼到新的工作簿,以便基本上將一組excel工作簿的結果合併到一個工作簿中。我的腳本現在運行它的方式將其複製並粘貼回原始工作簿。我需要更改哪些內容才能從一個工作簿中複製一個值並將其粘貼到新的工作簿中?XLwings,將值從一個工作簿複製到另一個工作簿?

# Import modules 
    import xlwings as xw 
    import os 

    # Creates list of all excels in the directory 
    excel_list = os.listdir(r"C:\Desktop\excel_folder") 

    # Opens a new blank workbook 
    wb = xw.Book() 

    # Count varible to adjust cell location 
    cell_count = 1 

    # Iterates through excel workbooks in the directroy 
    for excel in excel_list: 
     # Opens an excel from the directory 
     wb2 = xw.Book(r'C:\Desktop\excel_folder\{0}'.format(excel)) 
     # Grabs the needed value 
     copy_value = xw.Range('D2',wkb=wb2).value 
     # Addes the copy_value to the specified cell 
     xw.Range('A{0}'.format(cell_count),wkb=wb).value = copy_values 
     #Adjust the cell count 
     cell_count +=1 
     #Closes workbook 
     wb2.close() 

    print "Script complete" 
+0

我會這樣做,但這並不解決沒有任何值被複制到新工作簿的問題。 –

回答

0

您需要引用工作簿中的特定工作表來寫入。根據以下評論,xw.Range('A1',wkb=wb).value已被棄用。

import xlwings as xw 
import os 

# Creates list of all excels in the directory 
excel_list = os.listdir(r"Z:\sandbox\sheets") 

# Opens a new blank workbook and get Sheet1 
wb = xw.Book() 
sht = wb.sheets['Sheet1'] 

# Count varible to adjust cell location 
cell_count = 1 

# Iterates through excel workbooks in the directroy 
for excel in excel_list: 
    # Opens an excel from the directory 
    wb2 = xw.Book(r'Z:\sandbox\sheets\{0}'.format(excel)) 
    # Grabs the needed value 
    copy_value = wb2.sheets.active.range('B3') 
    # Addes the copy_value to the specified cell 
    sht.range('A{0}'.format(cell_count)).value = copy_value 
    #Adjust the cell count 
    cell_count +=1 
    #Closes workbook 
    wb2.close() 

print("Script complete") 
+0

非常感謝您的幫助,完美工作! –

+0

請注意,不推薦使用'xw.Range('B3',wkb = wb2).value'。使用'wb2.sheets.active.range('B3')'代替(或者是一個特定的表格而不是活動的表格) –

+0

@FelixZumstein:謝謝我編輯了這個答案。 –

相關問題