简体   繁体   English

如何使用openpyxl将Excel文件数组的最后一行导入另一个Excel

[英]How to import the last row from array of excel files to another excel using openpyxl

I have a list of excel files with similar last row. 我有与最后一行相似的Excel文件列表。 It contains private information about client (his name, surname, phone). 它包含有关客户的私人信息(他的名字,姓氏,电话)。 Each excel file correspond to each client. 每个excel文件对应于每个客户端。 I need to make one excel file with all data about every client. 我需要使用每个客户端的所有数据制作一个excel文件。 I decide to do it automatically, so looked to openpyxl library. 我决定自动执行此操作,因此转到openpyxl库。 I wrote such code, but it doesn't work correctly. 我写了这样的代码,但是不能正常工作。

In my test directory I have three files. 在我的测试目录中,我有三个文件。

import openpyxl
import os
import glob
from openpyxl import load_workbook
from openpyxl import Workbook
import openpyxl.styles
from openpyxl.cell import get_column_letter

def get_range(file, new_file):

    prize_sheet = prize_info.active
    sheet = f.active
    for row_num in range (1, len(file_array_reciever)):
        for col_num in range (3,sheet.max_column):
            prize_sheet.cell(row = row_num, column = col_num).value = sheet.cell(row = sheet.max_row, column = col_num).value

    return prize_info.save("Ex.xlsx")



#path to test files
path_kit = 'prize_input/kit'

#creating single document
prize_info = Workbook()

file_array_reciever = []

for file in glob.glob(os.path.join(path_kit, '*.xlsx')):
    file_array_reciever.append(file)


for file in glob.glob(os.path.join(path_kit, '*.xlsx')):
    file_array_reciever.append(file)
    f = load_workbook(filename = file)
    get_range(f,prize_info)

I think I have problem in my loop, because in output file I get three identical rows from first excel file 我认为我的循环有问题,因为在输出文件中,我从第一个excel文件中获得了三行相同的行

The function get_range() will overwrite the existing rows. 函数get_range()将覆盖现有行。

You should be able to use ws.rows[-1] to get the last row from any sheet. 您应该能够使用ws.rows[-1]从任何工作表中获取最后一行。 Something like 就像是

for f in file_array_receiver:
    sheet = f.active
    prize_sheet.append(f.rows[-1][:3])

Might be what you're looking for. 可能是您要找的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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