copy cell style openpyxl

后端 未结 3 1605
醉梦人生
醉梦人生 2020-12-01 20:47

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 cop

相关标签:
3条回答
  • 2020-12-01 21:21

    As of openpyxl 2.5.4, python 3.4: (subtle changes over the older version below)

    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)
    

    For 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
    
    0 讨论(0)
  • 2020-12-01 21:31

    May be this is the convenient way for most.

        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')
    
    0 讨论(0)
  • 2020-12-01 21:37

    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:

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

    FWIW this is how the optimized WorksheetCopy class does it in the _copy_cells method.

    0 讨论(0)
提交回复
热议问题