XLwings,将值从一个工作簿复制到另一个工作簿?
我需要遍历一堆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"
您需要引用工作簿中的特定工作表来写入。根据以下评论,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")
非常感谢您的帮助,完美工作! –
请注意,不推荐使用'xw.Range('B3',wkb = wb2).value'。使用'wb2.sheets.active.range('B3')'代替(或者是一个特定的表格而不是活动的表格) –
@FelixZumstein:谢谢我编辑了这个答案。 –
我会这样做,但这并不解决没有任何值被复制到新工作簿的问题。 –