Search code examples
pythonexcelconditional-formattingxlwings

Is there any way to keep conditional formatting after clearing content in excel sheet when using xlwings?


I have written a piece of code that clears all data from a sheet in an excel macro-enabled workbook and loads a data frame. After a lot of digging, I found out that the best library is Xlwings. However, after using clear() method, the existing formatting in the xlsm disappears. Is there any way to preserve the formatting?


Solution

  • Use Xlwings clear_contents() instead.

    The function clear_contents() reflects the same operation as in Excel.

    See the link for more details about the actions of the three Xlwings clear functions;

    • clear() Clears the content and the formatting of a Range.

    • clear_contents() Clears the content of a Range but leaves the formatting.

    • clear_formats() Clears the format of a Range but leaves the content.