简体   繁体   中英

XLwings, copying values from one workbook to another workbook?

I need to iterate through a bunch of excel workbooks and grab a value from each one and paste that value to a new workbook, so basically consolidating results from a bunch of excel workbooks to a single workbook . The way my script runs now it copies and pastes the value back to the original workbook. What do I need to change so I can copy a value from one workbook and paste it to the new workbook?

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

You need to refer to a specific sheet in the workbook to write into. As per the comment below, xw.Range('A1',wkb=wb).value is deprecated.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM