是否可以使用Python将工作表插入到现有工作簿中? [英] Is it possible to insert a worksheet into an existing workbook using Python?
问题描述
问题 使用Pandas和Python创建花式报告.
The Problem Creation of fancy reports using Pandas and Python.
建议的解决方案 使用包含模板工作表的模板xlsx文件,该文件的格式正确地引用了另一个预先填充的工作表,请删除该预先填充的工作表,然后从pandas中插入新的工作表.模板工作表将丢失恢复为#REF的链接,因此需要重命名这些链接.
Proposed Solution Using a template xlsx file containing a template sheet nicely formatted with references to another pre-populated worksheet, delete the pre-populated sheet and insert the new worksheet from pandas. The template sheet will lose the links reverting to #REF so these will need to be renamed.
我尝试过:
import os
import xlrd, xlwt
import envconfig
swb1 = xlrd.open_workbook(os.path.join(envconfig.REPORT_WRITER_PATH,'TEMPLATE.xls'), on_demand=True, formatting_info=True)
swb2 = xlrd.open_workbook(os.path.join(envconfig.REPORT_WRITER_PATH,'REPORT.xls'), on_demand=True, formatting_info=True)
swb1s1 = swb1.sheet_by_name('Template')
swb2s1 = swb2.sheet_by_name('Report')
twb = xlwt.Workbook()
sheet1 = twb.add_sheet(swb1s1)
sheet2 = twb.add_sheet(swb2s1)
twb.save("python_spreadsheet.xls")
上述错误:
sheet1 = twb.add_sheet(swb1s1)
File "C:\Users\pa003202\AppData\Local\Continuum\Anaconda3\lib\site-packages\xlwt\Workbook.py", line 366, in add_sheet
sheetname = sheetname.decode(self.encoding)
AttributeError: 'Sheet' object has no attribute 'decode'
sheetname = sheetname.decode(self.encoding)
AttributeError: 'Sheet' object has no attribute 'decode'
是否可以将熊猫中的数据注入到工作簿中或打开工作簿并插入工作表?
Is there a way to inject data from pandas into a workbook or to open a workbook and insert a sheet?
推荐答案
我通过创建所描述的模板解决了这个问题,并在此处使用了解决方案:
I solved this by creating a template as described and used the solution here:
建议的解决方案,使用模板xlsx文件(该模板包含格式正确且引用了另一个预先填充的工作表的模板),从pandas中插入新的工作表.如果插入的表具有相同的名称,则模板表不会丢失链接.
Proposed Solution Using a template xlsx file containing a template sheet nicely formatted with references to another pre-populated worksheet, insert the new worksheet from pandas. The template sheet does not lose the links providing the inserted sheet has same name.
解决方案:
查看如何写入现有的excel文件而不覆盖数据?,这适用于这种情况.
Look at How to write to an existing excel file without overwriting data? and this works for the scenario.
这篇关于是否可以使用Python将工作表插入到现有工作簿中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!