-1

Is it possible to add an existing worksheet object to a workbook object in openpyxl?

For better understanding: I DONT want to add a new sheet like this:

workbook.create_sheet('new sheet')

Instead i want to "merge" two existing sheets:

second_sheet = openpyxl.worksheet.worksheet.Worksheet()
workbook.add_sheed(second_sheet)
Florian
  • 95
  • 1
  • 8

1 Answers1

0

If you look at the source code you'll see this is possible but not advisable. Because things like styles are shared by different worksheets in the same workbook, these need to be managed by the workbook. This is also why it is not possible to move or copy worksheets between workbooks.

As you would know if you'd tried your own code, you must provide a parent workbook when creating a worksheet:

wb = Workbook()
ws = Worksheet(wb, "Sheetname")
wb._add_sheet(ws) # private API, so there is NO guarantee that this will always be possible
Abel
  • 688
  • 6
  • 19
Charlie Clark
  • 18,477
  • 4
  • 49
  • 55
  • Thanks, i didnt ran my own code because the "add_sheet" function i mentioned was an example, ididt know that this function actually existed. I also saw in the documentation of openpyxl that inserting worksheets from other workbooks is not possible, due to different styles etc. But this should not be a problem in my case, because all worksheets wich i want to merge are exactly identical only with different values in thier cells. – Florian Oct 28 '20 at 10:57
  • Well, as long as you bind the worksheet to the new workbook it should work but there is no guarantee. – Charlie Clark Oct 28 '20 at 11:09