简体   繁体   中英

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. It contains private information about client (his name, surname, phone). Each excel file correspond to each client. I need to make one excel file with all data about every client. I decide to do it automatically, so looked to openpyxl library. 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

The function get_range() will overwrite the existing rows.

You should be able to use ws.rows[-1] to get the last row from any sheet. 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.

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