Search code examples
pythonxlwings

How to select the whole sheet in xlwings


I am using xlwings. I want to copy the whole wb1.sheets(1) and paste to wb.sheets(1) A4 cell. Currently I have to set a very large cell Z100000. Is there any generic way to select the whole sheet rather than the unsafe region A1:Z10000?

import xlwings as xw
path = r'C:\Users\Desktop\test.xlsx'
app=xw.App(visible=False,add_book=False)
wb1 = app.books.open(path)
wb = app.books.add()
wb1.sheets(1).range('A1:Z10000').copy(wb.sheets(1).range('A4'))

I want to know how to select:

  1. The entire sheet i.e. Ctrl+A,

  2. The used part. Suppose wb1 write the area A1:F5. May be we can assume wb1 always begins from A1.


Solution

  • I believe you want to find the the range filled with contents, not necessarily all cells on the sheet. If so, simply use used_range:

    import xlwings as xw
    
    path = r"test.xlsx"
    
    wb = xw.Book(path)
    ws = wb.sheets[0]
    
    ws.used_range.select()
    

    But if you really want to select the entire sheet (including all empty cells), which sounds rather unusal, use the following code:

    import xlwings as xw
    
    path = r"test.xlsx"
    
    wb = xw.Book(path)
    ws = wb.sheets[0]
    
    ws.activate()
    ws.api.Cells.Select()