Append a sheet to an existing excel file using ope

2019-07-09 02:03发布

问题:

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?

回答1:

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


回答2:

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.