Search code examples
pythonexcelxlwings

Format Table in xlwings


How do you format a table in xlwings? For example, if I wanted to add the excel style "Light Blue, Table Style Light 2" to a Range object from xlwings.

Since it isn't in the xlwings docs, I believe it would look something like this (after connecting to the wb and everything):

xw.Range('A1').api. #Something goes here

As a follow-up question, how would one learn what sorts of options you have after grabbing the api object? The only places I have seen this done is in other SO questions and here which is basically just a compilation of SO answers to these sorts of questions.

(That way we don't have to keep bothering you, Felix ;) )


Solution

  • I found a solution. Sharing it with the community in case anyone else is interested in doing the same thing. Solution is based on a question asked and answered by himself here.

    import xlwings as xw
    
    wb = xw.('filename.xlsx')            # Initialize a WorkBook
    sht = wb.sheets['sheet_name']        # Grab the desired Sheet
    tbl = sht.api.ListObjects.add()      # Adds table to Excel (returning a Table)
    tbl.TableStyle = "TableStyleMedium5" # Set table styling
    

    NOTE: The weird part about this is that this puts a table starting wherever your cursor was in the Excel document (last time you saved it while open? Unsure about this). I had no luck trying to change the location of the cursor via Python. So if anyone figures out how to do that, I'd definitely be interested. For example, unless you can change the cursor location, you couldn't use my solution to make two separate tables on the same sheet.

    "Workaround" (AKA hack): I opted to save data from the sheet, delete and remake the sheet, and put the data back. On new sheets, your cursor is automatcially placed in A1, so calling the above code after moving the cursor in this way would make A1 (and surrounding cells) into the table, which is what I needed.