gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 21:27:04 25 4
gpt4 key购买 nike

我需要迭代一堆 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"

最佳答案

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

关于excel - XLwings,将值从一个工作簿复制到另一工作簿?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42424820/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com