Tuesday, February 1, 2022

excel opening with python and coloring the cells

 

from win32com.client.gencache import EnsureDispatch



    Application                  = EnsureDispatch("Excel.Application")

    Application.DisplayAlerts    = False

    Application.Visible          = True

    Application.AskToUpdateLinks = False

    Application.EnableEvents     = False

    

    mapping_wb                   = Application.Workbooks.Open(os.path.join(os.getcwd(), "test.xlsx"))

    ws                           = mapping_wb.Worksheets("color_check")

    

    ws.Range(f"A{1}").Value = "This is testing"

    

    #time.sleep(10)

    #ws.RefreshAll()

    #mapping_wb.FillColor("red")

    

    #ws.Cells(1,4).Value = "Coin Toss Results"  #This is Row D

    #ws.Range(f"A{4}").Value = "coint toss Results"

    

    cell = ws.Cells(2,4)

    cell.Interior.Color = rgbToInt((255,0,0))

    

    

    for i in range(2,5):   # Assuming there is Cell(D2)=1, Cell(D3)=0, Cell(D4)=-1

        cell = ws.Cells(i,4)

        if cell.Value < 0:

            cell.Interior.Color = rgbToInt((255,0,0)) # red

        elif cell.Value == 0:

            cell.Interior.Color = rgbToInt((211,211,211)) # grey

        elif cell.Value > 0:

            cell.Interior.Color = rgbToInt((0,255,0)) # green

        else:

            print('Error.')

        

    ws.Columns.AutoFit()

    mapping_wb.Save()

    

    print("refresh done")

No comments:

Post a Comment

python class topic video