I am trying to copy a sheet, default_sheet
, into a new sheet new_sheet
in the same workbook.
I did managed to create a new sheet and to copy the values from default sheet. How can I also copy the style of each cell into the new_sheet cells?
new_sheet = workbook.create_sheet()
new_sheet.title = sheetName
default_sheet = workbook.get_sheet_by_name('default')
new_sheet = workbook.get_sheet_by_name(sheetName)
for row in default_sheet.rows:
col_idx = float(default_sheet.get_highest_column())
starting_col = chr(65 + int(col_idx))
for row in default_sheet.rows:
for cell in row:
new_sheet[cell.get_coordinate()] = cell.value
<copy also style of each cell>
I am at the moment using openpyxl 1.8.2, but i have in mind to switch to 1.8.5.
One solution is with copy:
from copy import copy, deepcopy
new_sheet._styles[cell.get_coordinate()] = copy(
default_sheet._styles[cell.get_coordinate()])
May be this is the convenient way for most.
The
StyleableObject
implementation stores styles in a single list,_style
, and style properties on a cell are actually getters and setters to this array. You can implement the copy for each style individually but this will be slow, especially if you're doing it in a busy inner loop like I was.If you're willing to dig into private class attributes there is a much faster way to clone styles:
FWIW this is how the optimized
WorksheetCopy
class does it in the_copy_cells
method.As of openpyxl 2.5.4, python 3.4: (subtle changes over the older version below)
For openpyxl 2.1