Search code examples
pythonexcelwin32com

Python win32com method for word-wrap in Excel?


I need to write a function that will word wrap the contents of all sheets of an active Excel workbook. I have everything written except the necessary method. I am not able to find it anywhere. Does anyone have any knowledge on this?

from win32com.client import Dispatch
excel = Dispatch('Excel.Application')

def main():
    WordWrapColumns()

def WordWrapColumns():
    excel.ActiveWorkbook.Save()
    filename = excel.ActiveWorkbook.FullName
    wb = excel.Workbooks.Open(filename)
    #Activate all sheets
    active_sheets = wb.Sheets.Count
    for i in range(0,active_sheets):
        excel.Worksheets(i+1).Activate()
        # Word wrap all columns in sheet
        # What command goes here????
    #Save and close workbook
    wb.Save()
    wb.Close()
    excel.Quit()

if __name__ == '__main__':
    main()

Solution

  • Use "microsoft excel interop yourFunctionOrConstantOrClass" for web searches (works in google). In your case "microsoft excel interop word wrap" finds Range.WrapText property which suggests you should be able to do something like

    for i in range(0,active_sheets):
        ws = wb.Worksheets(i+1)
        ws.Columns.WrapText = True