简体   繁体   中英

openpyxl, how to close/shutdown .xlsx file/session after saving/using it?

As I understood, there are no such functions: del , clear cache or garbage in openpyxl, maybe I am wrong. The problem I'm facing: The problem occurs when I want to save 2nd generated.xlsx file. It somehow uses previous.xlsx file (and it's data) and can't merge some cells (from prev xlsx) since it does not have a write attribute.

So how I can close/shutdown previous xlsx. I even tried remove xlsx file before generating new one and it also did not help

code: (I dont have permission to post pics only links): pic 1: src(code, tree) how I am saving:

wb.save(filename=self.fileName)
wb.close()
  1. error

  2. class with id=1 xlsx

  3. class with id=4 xlsx, and my code some how wrote data from prev one(for ex: ECOLOGY 17:00-19:00) it should not work like that

  4. src code is here github

I'm not suprised that you can't reuse the same workbook object to save a file with another name. If you need to reuse this object, you can use workbook_obj.save(...);workbook_obj.close();workbook_obj=openpyxl.load_workbook(...) . I haven't tested this code, but it's my best guess.

I finally solved my problem. I followed @Michael Sohnen 's advice, But still, I'm not sure if openpyxl has a garbage-clearing feature or not. but it doesn't matter
Solution: Instead of creating a new xlsx file, I used an existing file if it exists, otherwise I generated a new one. That's all.
Explonation: As I understand it, he will download this particular file.xlsx, and openpyxl will know which file to work with, so we can be sure that we have avoided a data conflict.
final code:

from openpyxl import Workbook, load_workbook
from django.conf import settings
from os import path, walk

class Base:

    def __init__(self,filename:str):
        self.fileName=filename
        self.filePath=path.join(settings.BASE_DIR,'xlsxFiles',filename)
        self.folderDir=path.join(settings.BASE_DIR,'xlsxFiles')
        self.workBook=None

    def getWorkSheet(self):
        files=[]
        for (dPath,dNames,dFiles) in walk(self.folderDir):
            files.extend(dFiles)
        if self.fileName in files:
            with open(self.filePath, 'rb') as xlsx:
                self.workBook=load_workbook(xlsx)
                workSheet=self.workBook[self.workBook.sheetnames[0]]
                return workSheet
        else:
            self.workBook=Workbook()
            workSheet=self.workBook.active
            return workSheet

    def saveXlsx(self):
        self.workBook.save(filename=self.filePath)
        self.workBook.close()

old one:

class Base:
    wb=Workbook()
    sheet=wb.active

moreover I was saving generated.xlsx in in another code.py

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