复制单元格样式openpyxl

时间:2014-04-28 04:00:14

标签: python openpyxl

我正在尝试将工作表default_sheet复制到同一工作簿中的新工作表new_sheet中。

我设法创建了一个新工作表,并从默认工作表中复制了这些值。我怎样才能将每个单元格的样式复制到new_sheet单元格中?

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>

我目前正在使用openpyxl 1.8.2,但我想切换到1.8.5。

一个解决方案是复制:

from copy import copy, deepcopy

new_sheet._styles[cell.get_coordinate()] = copy(
        default_sheet._styles[cell.get_coordinate()])

3 个答案:

答案 0 :(得分:16)

从openpyxl 2.5.4开始,python 3.4 :(对下面的旧版本进行细微更改)

new_sheet = workbook.create_sheet(sheetName)
default_sheet = workbook['default']

from copy import copy

for row in default_sheet.rows:
    for cell in row:
        new_cell = new_sheet.cell(row=cell.row, column=cell.col_idx,
                value= cell.value)
        if cell.has_style:
            new_cell.font = copy(cell.font)
            new_cell.border = copy(cell.border)
            new_cell.fill = copy(cell.fill)
            new_cell.number_format = copy(cell.number_format)
            new_cell.protection = copy(cell.protection)
            new_cell.alignment = copy(cell.alignment)

对于openpyxl 2.1

new_sheet = workbook.create_sheet(sheetName)
default_sheet = workbook['default']

for row in default_sheet.rows:
    for cell in row:
        new_cell = new_sheet.cell(row=cell.row_idx,
                   col=cell.col_idx, value= cell.value)
        if cell.has_style:
            new_cell.font = cell.font
            new_cell.border = cell.border
            new_cell.fill = cell.fill
            new_cell.number_format = cell.number_format
            new_cell.protection = cell.protection
            new_cell.alignment = cell.alignment

答案 1 :(得分:4)

StyleableObject实现将样式存储在单个列表_style中,单元格上的样式属性实际上是该数组的获取器和设置器。您可以分别为每种样式实现副本,但这会很慢,特别是如果您像以前那样在繁忙的内部循环中进行复制。

如果您愿意挖掘私有类的属性,则有一种更快的克隆样式的方法:

if cell.has_style:
    new_cell._style = copy(cell._style)

首先,这是优化的WorksheetCopy类如何在_copy_cells方法中实现的方法。

答案 2 :(得分:3)

对于大多数人来说,这可能是方便的方式。

    from openpyxl import load_workbook
    from openpyxl import Workbook
    read_from = load_workbook('path/to/file.xlsx')
    read_sheet = read_from.active
    write_to = Workbook()
    write_sheet = write_to.active
    write_sheet['A1'] = read_sheet['A1'].value
    write_sheet['A1'].style = read_sheet['A1'].style
    write_to.save('save/to/file.xlsx')