【问题标题】:Pandas append sheet to workbook if sheet doesn't exist, else overwrite sheet如果工作表不存在,熊猫将工作表附加到工作簿,否则覆盖工作表
【发布时间】:2019-07-03 15:40:01
【问题描述】:

我正在使用 pandas 更新现有的 Excel 工作簿。使用ExcelWriter 对象时,如果工作表存在,我可以覆盖工作表并创建新工作表吗?我添加了新工作表的代码,但是当我尝试覆盖现有工作表时,它会附加一个名称略有不同的新工作表(例如:如果工作表“data1”存在,运行代码会附加一个名为“data1 1”的新工作表) .

import pandas as pd
import openpyxl
path = 'test-out.xlsx'
book = openpyxl.load_workbook(path)
df1 = pd.DataFrame({'a': range(10), 'b': range(10)})
writer = pd.ExcelWriter(path, mode='a')
writer.book = book
df1.to_excel(writer, sheet_name='data1')
writer.save()

【问题讨论】:

  • 您是否尝试过检查工作表是否存在?并在to_excel之前删除它(或清除其内容)?
  • 我想我必须这样做才能覆盖现有的工作表。谢谢!

标签: python excel pandas


【解决方案1】:

将工作表传递给writerwriter.sheets = dict((ws.title, ws) for ws in book.worksheets)

import pandas as pd
import openpyxl
path = 'test-out.xlsx'
book = openpyxl.load_workbook(path)
df1 = pd.DataFrame({'a': range(10), 'b': range(10)})
writer = pd.ExcelWriter(path, mode='a')
writer.book = book
writer.sheets = dict((ws.title, ws) for ws in book.worksheets)
df1.to_excel(writer, sheet_name='data1')
writer.save()

编辑:

好像你甚至不需要mode='w'writer = pd.ExcelWriter(path, mode='a') 还在工作......

【讨论】:

  • fyi, pd.ExcelWriter(exl[i], engine="openpyxl", mode="a", if_sheet_exists="replace") 对任务执行相同的操作。但由于某种原因,它适用于 windows env 而不是 linux(我检查了文件权限不是原因)。在 linux 中,它创建了新的工作表,而不是覆盖现有的工作表。但是接受的答案在 Windows 和 linux 中都可以正常工作。
猜你喜欢
  • 2021-10-04
  • 1970-01-01
  • 2017-12-21
  • 1970-01-01
  • 2018-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多