Python - Call Interface folder merge multiple Excel table

At work often encountered need to open many excel spreadsheet, then the combined demand, combined and requested format must be authentic reserved. Using VBA code can be relatively easy to solve, and now we look at how to achieve Python.

On the code:

from openpyxl import Workbook
from win32com.client import Dispatch
import os
import datetime


def copy_excel_file(source_file_list, destination_file):
    run_app = Dispatch('Excel.Application')
    Open run_app.Visible = False # True change can be seen excel window

    for file in source_file_list:
        source_workbook = run_app.Workbooks.Open(Filename=file)
        destination_workbook = run_app.Workbooks.Open(Filename=destination_file)

        source_workbook.Worksheets(1).Copy(Before=destination_workbook.Worksheets(1))
        destination_workbook.Close(SaveChanges=True)

    run_app.Quit()


class parameterGenerator:

    def __init__(self):
        # self.directory_path = directory_path
        self.file_lists = []

    def creat_xlsx(self, directory_path):
        obj = Workbook()
        if not os.path.exists(directory_path + os.sep + 'joined'):
            os.mkdir(directory_path + os.sep + 'joined')
        date = str(datetime.datetime.today())[0:10]
        obj.save(directory_path + os.sep + 'joined' + os.sep + 'joined {}.xlsx'.format(date))

    def get_file_list(self, directory_path):
        entry_lists = os.scandir(directory_path)
        for entry_list in entry_lists:
            if entry_list.is_file():
                if '~$' not in entry_list.path:
                    self.file_lists.append(entry_list.path)
        return self.file_lists

    def run(self, directory_path):
        file_lists = self.get_file_list(directory_path)
        self.creat_xlsx(directory_path)
        destination_file = str(self.get_file_list(directory_path + os.sep + 'joined')[-1])
        file_lists.pop(-1)
        return file_lists, destination_file


if __name__ == "__main__":
    directory_path = r'D: \ Excel directory '
    param = parameterGenerator()
    source_file_list, destination_file = param.run(directory_path)
    copy_excel_file(source_file_list, destination_file)


The output is a new folder 'joined' folder, a file which has 'joined xxxx-xx-xx.xlsx' combined as follows:

20200329011341

20200329011353

Currently we found two problems that need attention:

1. The need to merge the files can not have a hidden form, otherwise, skips the file;

2. File names not unexpected token characters, such as brackets and the like.


Finally, the call interface a bit slow, still have the opportunity to see what can be achieved if openpyxl, were combined format. xlwings is similar implementation, estimated speed is almost slow.

Guess you like

Origin www.cnblogs.com/johnthegreat/p/12590592.html