0

I want to close/quit/terminate a particular excel file only. Based on my script, it closes all open/active excel files. My intention is to force close a particular file only. How to resolve it?

For Example, In my case I open, more than 3 excel files in active mode(open), Now I Run the script, to append data in a particular excel file (example.xlxs).It's in open mode, so raises an error code 13, permission error. so my necessity to forcibly close that particular file programmatically. But, it closes all open excel files.

Googleing so many things including xlwings.quit() . xlwings.quit() also closed all open/active excel files.

please suggest a better way to resolve it.

import sys
import os
from PyQt5.QtWidgets import QWidget,QApplication,QMessageBox,QSizePolicy
from PyQt5.QtGui import QIcon

from openpyxl import load_workbook
from win32com.client import Dispatch

my_filename = r'd:\me\openpyxl\example.xlsx'
companies = [['name1','address1','tel1','web1'], ['name2','address2','tel2','web2']]

class Force_to_close_open_excel_files(QWidget):
    def __init__(self):
        super(). __init__()
        self.show_errormsg = "show"
        self.append_data()

    def append_data(self):
        try:
            active_workbook = load_workbook(filename=my_filename)
            active_work_sheet = active_workbook.active
            active_workbook.save(filename=my_filename)

            for info in companies:
                active_work_sheet.append(info)
            print("data Added Sucessfully")
            active_workbook.save(filename=my_filename)

        except Exception as e:
            if self.show_errormsg == 'show':
                self.handle_error(e)
            else:
                pass

    def handle_error(self, error):
        exc_type, exc_value, exc_traceback = sys.exc_info()
        filenamewithpath = exc_traceback.tb_frame.f_code.co_filename
        head, tail = os.path.split((filenamewithpath))
        lineno = exc_traceback.tb_lineno
        name = exc_traceback.tb_frame.f_code.co_name
        type = exc_type.__name__
        message = exc_value
        error_no = ([x[0] for x in [message.args]])

        nl = '\n'
        kk = f'File Name : {tail[:-3]}{nl}' \
             f'Line No. : {lineno}{nl}' \
             f'Type : {type}{nl}' \
             f'Error Code : {error_no[0]}{nl}'\
             f'Name : {name}{nl}'

        self.msg = QMessageBox()
        self.msg.setSizePolicy(QSizePolicy.MinimumExpanding,QSizePolicy.MinimumExpanding)
        self.msg.setWindowTitle("  Error/Bugs Information")
        self.msg.setWindowIcon(QIcon('icon\close006.png'))
        self.msg.setText(f'{type} - Line No {lineno}')
        self.msg.setIcon(QMessageBox.Information)
        self.msg.setStandardButtons(QMessageBox.Ok)
        self.msg.addButton(QMessageBox.Close)
        self.btn_focestop = self.msg.button(QMessageBox.Close)
        self.btn_focestop.setText("Force to Close - Excel Files")
        self.msg.setDefaultButton(QMessageBox.Ok)
        self.msg.setInformativeText("")
        self.msg.setDetailedText(kk)
        self.msg.show()
        self.msg.exec_()

        if self.msg.clickedButton() ==  self.btn_focestop:
            excel = Dispatch("Excel.Application")
            excel.Visible = False
            workbook = excel.Workbooks.Open(my_filename)
            map(lambda book: book.Close(False), excel.Workbooks)
            excel.Quit()
            self.append_data()

def main():
    app = QApplication(sys.argv)
    ex = Force_to_close_open_excel_files()
    # ex.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()
ekhumoro
  • 115,249
  • 20
  • 229
  • 336
Kumar
  • 592
  • 6
  • 18

1 Answers1

0

Based on this Question and ig0774 solution, I will try the following, and its works for me

 if self.msg.clickedButton() ==  self.btn_focestop:
        excel = Dispatch("Excel.Application")
        # excel.Visible = False
        workbook = excel.Workbooks.Open(my_filename)
        # map(lambda book: book.Close(False), excel.Workbooks)
        # excel.Quit()
        workbook.Close(True)
Kumar
  • 592
  • 6
  • 18