Python遍历excel文件-将输出粘贴到先前的输出下方

问题描述 投票:0回答:1

我的python代码几乎不需要帮助。我有两个主要的擅长VBA计算和最终输出。其余的都来自具有相同数据类型的文件夹,所有Excel都具有相同的单元格数据范围。

输出步骤步骤1 excel文件夹-每个文件夹都会填充vba文件2上的输入表。步骤2一旦一个excel填充了工作表,我就需要它从输出工作表中提取数据。步骤3然后,我将需要对所有Excel重复此步骤,其中步骤2的每个输出都将输入数据的最后一位以下。

我目前在下面,第三个输出似乎没有被复制和粘贴,但是我认为这是excel3代码的问题,没有选择正确的工作表,但不知道。我把测试纸和原始纸1和2一起离开了

仅具有1个sheet1的excel 1带有2个表单的excel 2(sheet1的粘贴和sheet2的输出)也只有1个sheet1的excel 3。

我还想知道是否可以在其中添加Tkinter,以便您可以选择一个文件路径,但我认为最好在此之前完成。

import openpyxl as xl

# excel file - this needs to be accessing a folder and looping through each excel in the file
excel ="C:/Users/eldri/OneDrive/Desktop/trading.xlsx"
wb1 = xl.load_workbook(excel)
ws1 = wb1.worksheets[0]

# vba file 2
excel1 ="C:/Users/eldri/OneDrive/Desktop/test.xlsx"
wb2 = xl.load_workbook(excel1)
ws2 = wb2.active

# final output file 3
excel2 ="C:/Users/eldri/OneDrive/Desktop/test.xlsx"
wb3 = xl.load_workbook(excel2)
ws3 = wb3.worksheets[1]

# final output file 3
excel3 ="C:/Users/eldri/OneDrive/Desktop/final.xlsx"
wb4 = xl.load_workbook(excel3)
ws4 = wb4.active

# calculate total number of rows and 
# columns in source excel file 
mr = ws1.max_row 
mc = ws1.max_column

# second copy and paste
sr = ws2.max_row
sc = ws2.max_column

# copying the cell values from source 
# excel file to destination excel file 
for i in range (1, mr + 1): 
    for j in range (1, mc + 1): 
        # reading cell value from source excel file 
        c = ws1.cell(row = i, column = j) 

        # writing the read value to destination excel file 
        ws2.cell(row = i, column = j).value = c.value

# second copy and paste
for i in range (1, sr + 1):
    for j in range (1, sc + 1):
        # reading cell value from source excel file
        d = ws3.cell(row = i, column = j)

        # writing the read value to destination excel file
        ws4.cell(row = i, column = j).value = d.value


wb2.save(str(excel1))
wb4.save(str(excel3))

非常感谢您的帮助。

python python-3.x excel loops pycharm
1个回答
0
投票

我认为您保存的文件错误。这个:

wb2.save(str(excel1))
wb4.save(str(excel3))

应该是:

wb3.save(str(excel2))
wb4.save(str(excel3))
© www.soinside.com 2019 - 2024. All rights reserved.