Is it possible to insert a worksheet into an existing workbook using Python?

假如想象 提交于 2019-12-08 07:04:33

问题


The Problem Creation of fancy reports using Pandas and Python.

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.

I tried:

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")

The above errors with:

  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?


回答1:


I solved this by creating a template as described and used the solution here:

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.

Solution:

Look at How to write to an existing excel file without overwriting data? and this works for the scenario.



来源:https://stackoverflow.com/questions/34945456/is-it-possible-to-insert-a-worksheet-into-an-existing-workbook-using-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!