XLwings,将值从一个工作簿复制到另一个工作簿?

XLwings, copying values from one workbook to another workbook?

我需要遍历一堆 excel 工作簿并从每个工作簿中获取一个值并将该值粘贴到一个新工作簿中,所以基本上是将一堆 excel 工作簿的结果合并到一个工作簿。我的脚本现在运行的方式是将值复制并粘贴回原始工作簿。我需要更改什么才能从一个工作簿复制值并将其粘贴到新工作簿?

    # 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"

您需要参考工作簿中的特定sheet才能写入。根据下面的评论,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")