[Python] reading worksheet and preserving conditional formatting

Discussão em 'Python' iniciado por Stack, Julho 9, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to read an excel worksheet with openpyxl. I think I am losing the conditional formatting information in the sheet when I read it like so:

    xl = openpyxl.load_workbook(filename)


    When I read all cells in the file and save it. I get a spreadsheet in which none of the conditional formatting is implement.

    I can find many ways of adding conditional formatting to a spreadsheet at http://openpyxl.readthedocs.org/en/latest/formatting.html

    But I cannot find a way to read conditional formatting information in an existing worksheet.

    The specific code I am using for doing the read and write is,

    import openpyxl as xl

    xlf = xl.load_workbook(r'd:\test\book1.xlsx')
    sh = xlf.get_sheet_by_name('Sheet1')
    allcells = sh.get_cell_collection()

    wb = xl.Workbook()
    ws = wb.create_sheet()

    for c in allcells:
    row = c.row
    col = xl.cell.column_index_from_string(c.column)
    new_cell = ws.cell(row=row, column=col)
    new_cell.value = c.value
    new_cell.style = c.style.copy()

    ws.title = 'test'
    wb.save(r'd:\test\book1w.xlsx')

    Continue reading...

Compartilhe esta Página