是否可以使用 Python 将工作表插入现有工作簿?

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

问题 使用 Pandas 和 Python.

创建精美报告

建议的解决方案 使用包含模板 sheet 的模板 xlsx 文件,该模板的格式很好地引用了另一个预填充的作品 sheet,删除预填充的 sheet 并从中插入新作品sheet pandas。模板 sheet 将丢失恢复为 #REF 的链接,因此需要重命名这些链接。

我试过了:

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'

有没有办法将 pandas 中的数据注入工作簿或打开工作簿并插入 sheet?

我通过创建一个模板解决了这个问题,并使用了这里的解决方案:

建议的解决方案 使用包含模板 sheet 的模板 xlsx 文件,其格式很好地引用了另一个 pre-populated 作品sheet,插入pandas 的新作品sheet。模板 sheet 不会丢失链接,前提是插入的 sheet 具有相同的名称。

解决方法:

查看 How to write to an existing excel file without overwriting data?,这适用于场景。