Search code examples
pythonexcelpython-2.7win32com

Load existing Excel file, change the zoom level for all sheets, and remove gridlines


I'm using win32com to load an existing Excel doc. I'm currently able to loop through the sheets and remove text wrapping and autofit columns.

import win32com.client
excel = win32com.client.Dispatch('Excel.Application')
excel.Visible = False # I want to keep it this way


path = "C:\\Users\\username\\Documents\\DDA"
wb_new = excel.Workbooks.Open(path + '\\new_file.xlsx')

# wb_new is a file with three tabs, with one value in cell A1 each... 
# ...if you want to recreate it.

active_sheets = wb_new.Sheets.Count
for i in range(0, active_sheets):
    ws = wb_new.Worksheets(i + 1)
    ws.Columns.WrapText = False
    ws.Columns.AutoFit()

Next, I'd like to adjust the zoom level and remove gridlines for all sheets. I haven't found a solution that accomplishes this without making excel.Visible = True. I'm open to using a package from python-excel.org but I haven't found anything.

I came across the openpyxl.worksheet.views subpackage which contains the SheetView class, but it doesn't seem to be useful for existing documents.


Solution

  • import win32com.client
    excel = win32com.client.Dispatch('Excel.Application')
    excel.Visible = False # I want to keep it this way
    
    
    path = "C:\\Users\\username\\Documents\\DDA"
    wb_new = excel.Workbooks.Open(path + '\\new_file.xlsx')
    
    # wb_new is a file with three tabs, with one value in cell A1 each... 
    # ...if you want to recreate it.
    
    active_sheets = wb_new.Sheets.Count
    for i in range(0, active_sheets):
        ws = wb_new.Worksheets(i + 1)
        ws.Columns.WrapText = False
        ws.Columns.AutoFit()
        ws.Activate() # answer starts here
        excel.ActiveWindow.Zoom = 80
        excel.ActiveWindow.DisplayGridlines = False