简体   繁体   中英

Append a sheet to an existing excel file using openpyxl

I saw this post to append a sheet using xlutils.copy:

https://stackoverflow.com/a/38086916/2910740

Is there any solution which uses only openpyxl?

I found solution. It was very easy:

def store_excel(self, file_name, sheet_name):
    if os.path.isfile(file_name):
        self.workbook = load_workbook(filename = file_name)
        self.worksheet = self.workbook.create_sheet(sheet_name)
    else:
        self.workbook = Workbook()
        self.worksheet = self.workbook.active
        self.worksheet.title = time.strftime(sheet_name)
    .
    .
    .
    self.worksheet.cell(row=row_num, column=col_num).value = data

I would recommend storing data in a CSV file, which is a ubiquitous file format made specifically to store tabular data. Excel supports it fully, as do most open source Excel-esque programs.

In that case, it's as simple as opening up a file to append to it, rather than write or read:

with open("output.csv", "a") as csvfile:
    wr = csv.writer(csvfile, dialect='excel')
    wr.writerow(YOUR_LIST)

As for Openpyxl:

end_of_sheet = your_sheet.max_row

will return how many rows your sheet is so that you can start writing to the position after that.

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