【问题标题】:Append a sheet to an existing excel file using openpyxl使用 openpyxl 将工作表附加到现有的 excel 文件
【发布时间】:2017-01-22 18:49:04
【问题描述】:

我看到这篇文章是使用 xlutils.copy 附加一张工作表:

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

有没有只使用 openpyxl 的解决方案?

【问题讨论】:

  • 你能更具体地说明你想做什么吗?
  • 我有一个包含多个工作表的 excel 文件,我想在该文件的末尾添加一个新工作表并在其中插入一些数据。
  • 听起来你只需要阅读 openpyxl 文档。

标签: python openpyxl


【解决方案1】:

我找到了解决方案。这很容易:

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】:

    我建议将数据存储在 CSV 文件中,这是一种普遍存在的文件格式,专门用于存储表格数据。 Excel 完全支持它,大多数开源 Excel 式程序也是如此。

    在这种情况下,它就像打开一个文件以追加到它一样简单,而不是写入或读取:

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

    至于 Openpyxl:

    end_of_sheet = your_sheet.max_row
    

    将返回您的工作表的行数,以便您可以在此之后开始写入该位置。

    【讨论】:

    • 谢谢,但我需要将数据存储在excel中。我还需要将新数据附加到新工作表中。
    猜你喜欢
    • 2015-11-10
    • 2018-06-20
    • 1970-01-01
    • 2016-05-23
    • 2015-11-18
    • 2021-10-15
    • 2018-03-22
    • 2022-11-16
    • 1970-01-01
    相关资源
    最近更新 更多