加载现有Excel文件,更改所有工作表的缩放级别,并删除网格线

时间:2016-06-03 18:11:11

标签: python excel python-2.7 win32com

我正在使用win32com加载现有的Excel文档。我现在能够遍历工作表并删除文本换行和自动调整列。

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()

接下来,我想调整缩放级别并删除所有工作表的网格线。我没有找到一个解决方案来实现这一点,而没有excel.Visible = True。我愿意使用来自python-excel.org的软件包,但我没有找到任何内容。

我遇到了包含openpyxl.worksheet.views类的SheetView子包,但它似乎对现有文档没有用。

1 个答案:

答案 0 :(得分:0)

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