Pandas to_excel 隐藏了工作表,还是有效地隐藏了 excel 标签?
Pandas to_excel with sheets being hidden, or efficiently hiding excel tabs?
创建并保存 df:
df = pd.DataFrame({'Attribute1': ['A', 'B'], 'Attribute2': ['X', 'Y']})
filename = 'test.xlsx'
writer = pd.ExcelWriter(filename, engine='xlsxwriter')
with writer:
df.to_excel(writer, sheet_name='df')
df.to_excel(writer, sheet_name='2nd tab')
我想在 sheet 条件中添加类似 hidden=True
的内容,但是 pandas doesn't seem to support this.
我们可以 do this manually with openpyxl,但是对于大文件来说速度太慢了:
from openpyxl import load_workbook
wb = load_workbook(filename)
wb["df"].sheet_state='hidden'
wb.save(filename)
显然最好的解决方案是不使用 Excel,但这就是要求。执行此操作的实用方法是什么?
您需要获取 XlsxWriter 工作表对象的句柄才能隐藏它。像这样:
import pandas as pd
df = pd.DataFrame({'Attribute1': ['A', 'B'],
'Attribute2': ['X', 'Y']})
filename = 'test.xlsx'
writer = pd.ExcelWriter(filename, engine='xlsxwriter')
with writer:
df.to_excel(writer, sheet_name='df')
df.to_excel(writer, sheet_name='2nd tab')
# Get a handle to the worksheet.
worksheet = writer.sheets['2nd tab']
worksheet.hide()
输出:
如果您想隐藏第一个工作表,您需要做一些额外的工作,因为 Excel 不允许您隐藏“活动”工作表,通常是第一个工作表。在这种情况下,您还需要“激活”另一个工作表。像这样:
with writer:
df.to_excel(writer, sheet_name='df')
df.to_excel(writer, sheet_name='2nd tab')
worksheet = writer.sheets['df']
worksheet.hide()
worksheet = writer.sheets['2nd tab']
worksheet.activate()
输出:
有关详细信息,请参阅 Working with Python Pandas and XlsxWriter
另请注意,示例中的 datetime_format
参数不正确。这是作者 class 的 属性 而不是 to_excel()
方法。我把它从上面的例子中遗漏了。
创建并保存 df:
df = pd.DataFrame({'Attribute1': ['A', 'B'], 'Attribute2': ['X', 'Y']})
filename = 'test.xlsx'
writer = pd.ExcelWriter(filename, engine='xlsxwriter')
with writer:
df.to_excel(writer, sheet_name='df')
df.to_excel(writer, sheet_name='2nd tab')
我想在 sheet 条件中添加类似 hidden=True
的内容,但是 pandas doesn't seem to support this.
我们可以 do this manually with openpyxl,但是对于大文件来说速度太慢了:
from openpyxl import load_workbook
wb = load_workbook(filename)
wb["df"].sheet_state='hidden'
wb.save(filename)
显然最好的解决方案是不使用 Excel,但这就是要求。执行此操作的实用方法是什么?
您需要获取 XlsxWriter 工作表对象的句柄才能隐藏它。像这样:
import pandas as pd
df = pd.DataFrame({'Attribute1': ['A', 'B'],
'Attribute2': ['X', 'Y']})
filename = 'test.xlsx'
writer = pd.ExcelWriter(filename, engine='xlsxwriter')
with writer:
df.to_excel(writer, sheet_name='df')
df.to_excel(writer, sheet_name='2nd tab')
# Get a handle to the worksheet.
worksheet = writer.sheets['2nd tab']
worksheet.hide()
输出:
如果您想隐藏第一个工作表,您需要做一些额外的工作,因为 Excel 不允许您隐藏“活动”工作表,通常是第一个工作表。在这种情况下,您还需要“激活”另一个工作表。像这样:
with writer:
df.to_excel(writer, sheet_name='df')
df.to_excel(writer, sheet_name='2nd tab')
worksheet = writer.sheets['df']
worksheet.hide()
worksheet = writer.sheets['2nd tab']
worksheet.activate()
输出:
有关详细信息,请参阅 Working with Python Pandas and XlsxWriter
另请注意,示例中的 datetime_format
参数不正确。这是作者 class 的 属性 而不是 to_excel()
方法。我把它从上面的例子中遗漏了。