【问题标题】:Dataframe to sheet and save in xlsm in a specific sheet数据框到工作表并保存在特定工作表中的 xlsm
【发布时间】:2021-12-18 06:03:14
【问题描述】:

我正在尝试从 pandas 数据框中保存数据,然后将其保存到 xlsm 文件。但是,我有一个问题。我找到了一种获取数据到openpyxl的方法,但是如何保存呢?

    from openpyxl.utils.dataframe import dataframe_to_rows
    import pandas as pd
    from openpyxl import load_workbook

    prices = pd.DataFrame({'name': ['Fred', 'Jane', 'Alice', 'Margaret'], 
         'street': ['Baker Street', 'Downing Street', 'Baker Street', 
         'Castle Street'],
         'stamp': ['', 'T03', '', ''],
         'city': ['', 'London', '', ''],
         'other irrelevant columns for this task' : [1, 2, 3, 4]
          })
    book = load_workbook('test.xlsm', keep_vba=True)
    ws = book.active
    rows = dataframe_to_rows(prices, index=False)
    for r_index, row in enumerate(rows, 1):
        for c_index, value in enumerate(row, 1):
            ws.cell(row=r_index, column=c_index, value=value)
    book.save('test.xlsm')

This is the error I am getting: KeyError: "There is no item named '[Content_Types].xml' in the archive"

错误的完整追溯

Traceback (most recent call last):
  File "PATH\scripts\prices.py", line 57, in <module>
    book = openpyxl.load_workbook('test.xlsm')
  File "PATHPython39\lib\site-packages\openpyxl\reader\excel.py", line 317, in load_workbook
    reader.read()
  File "PATHPython39\lib\site-packages\openpyxl\reader\excel.py", line 276, in read
    self.read_manifest()
  File "PATHPython39\lib\site-packages\openpyxl\reader\excel.py", line 134, in read_manifest
    src = self.archive.read(ARC_CONTENT_TYPES)
  File "PATHPython39\lib\zipfile.py", line 1463, in read
    with self.open(name, "r", pwd) as fp:
  File "PATHPython39\lib\zipfile.py", line 1502, in open
    zinfo = self.getinfo(name)
  File "PATHPython39\lib\zipfile.py", line 1429, in getinfo
    raise KeyError(
KeyError: "There is no item named '[Content_Types].xml' in the archive"

【问题讨论】:

  • 您的示例同时使用bookwb 作为工作簿。 prices 也没有提供。使用rows 的随机数据我无法重现该错误。请提供minimal, reproducible example
  • 好的,我已经更正了代码。价格是数据框。我想用新的数据框替换 xlsm 中的任何内容。
  • 我怀疑文件有缺陷。请提供错误的完整回溯。
  • 没问题,我已经添加了完整的回溯。我觉得文件没问题,我可以用excel打开它,用excel打开它没有错误
  • 同样,按照上面提供的方式运行代码不会重现错误。运行此代码是否会产生您的回溯中显示的错误?

标签: python-3.x pandas openpyxl


【解决方案1】:

我的错误是我在将 dataframe.to_excel 写入 XLSM 文件之前保存了它。当我注释掉 prices.to_excel('test.xlsx') 时,代码有效。

所以我发现我不能拥有的是:

prices.to_excel('test.xlsx')

当我评论它时,它起作用了。

#prices.to_excel('test.xlsx') 

【讨论】:

  • 您好,恭喜您第一次回答。为了让人们更容易,请尽量简明扼要地回答如何解决问题。这将允许人们直接发现修复
  • @Aylinn 这如何回答您的问题?您的问题中没有prices.to_excel('text.xlsx')
  • 我想让它更简单,以免编写整个代码,当我问它是否重要时,我并没有想到它。
猜你喜欢
  • 2021-05-11
  • 2020-03-09
  • 2020-11-05
  • 2016-02-26
  • 1970-01-01
  • 2019-12-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多