0

i got the following .xlsx file.

I would like to enter the yellow marked string in bold in the following image.

enter image description here

The condition is that there is a string in the "Name1" column and there must be no string in the "Name2" column -> then change the string in the "Name1" column to bold.

How do I have to change the following code snippet to achieve this?

 worksheet_tc.conditional_format("B2:B5000", {'type':'cell',
                                     'criteria': ''
                                     'format': format_bold})
mika
  • 173
  • 2
  • 16
  • 1
    `xlsxwriter` is a wrong choice in case of already existing file. This package doesn't allow you to modify data. `openpyxl` or `xlwings` is the choice in this case. As for the main part - a formula to apply in conditional formatting - this question is a duplicate, e.g. see [this post](https://stackoverflow.com/questions/57710926/how-to-add-a-rule-in-one-column-based-off-the-data-of-another/57741686#57741686) or [this one](https://stackoverflow.com/questions/38438520/conditional-formatting-with-formula-using-relative-references) – Vitalizzare Oct 26 '22 at 20:26

1 Answers1

2

So the trick with stuff like this is to make the conditional formatting work in Excel, and then just copying the formula.

I created a new workbook with a new worksheet, where the columns B and H match yours (more or less).

The applied conditional formatting rule does exactly what you want. It could be simplified to this: formula = '=$H2=""' but then technically empty cells in column B would be bolded as well with your data.

import xlsxwriter


with xlsxwriter.Workbook("testing123.xlsx") as workbook:
    # create worksheet
    worksheet_tc = workbook.add_worksheet()
    # set column names
    worksheet_tc.write(0, 1, "Name1")
    worksheet_tc.write(0, 7, "Name2")
    # write some data
    for x in range(1, 20):
        if x % 3 != 0:
            worksheet_tc.write(x, 1, f"Something{x+1}")
            if x % 2 == 0:
                worksheet_tc.write(x, 7, f"Something{x+1}")

    # add format
    format_bold = workbook.add_format({"bold": True})

    # the formula below checks if the cell in column B contains anything,
    # and if the cell in column H is empty
    formula = '=AND($B2<>"", $H2="")'
    worksheet_tc.conditional_format(
        "B2:B5000", {"type": "formula", "criteria": formula, "format": format_bold}
    )

resulting Excel sheet:

enter image description here

resulting conditional formatting rules on the sheet:

enter image description here

Edo Akse
  • 4,051
  • 2
  • 10
  • 21