当xlwings模块的sheet对象提供的属性和函数不能满足需求时,可以通过api属性将sheet对象转换为EXCEL VBA中的worksheet对象,再通过调用worksheet对象的属性和函数来完成所需的工作表操作。
3.3.1 Protect()函数–保护工作表
表达式.api.Protect(Password,Contents)
- Password:指定保护工作表的密码;
- Contents:当参数为True,表示工作表内容不被修改。
# 保护工作薄中的指定工作表
import xlwings as xw
app = xw.App(visible=Flase, add_book=Flase)
workbook = app.books.open('./examle.xlsx')
worksheet = workbook.sheets['sheet1']
worksheet.api.Protect(Password='111', Contents=True)
wrokbook.save()
workbook.close()
app.quit()
# 取消对工作表的保护
worksheet.api.Unpotect(Password='111')
3.3.2 PrintOut()–打印工作表
表达式.api.PringtOut(Copies,ActivePrinter,Collate)
- Copies:指定打印的份数
- ActivePrinter:指定打印机的名称
- Collate:为True时,逐份打印
import xlwings as xw
app = xw.App(visible=Flase, add_book=Flase)
workbook = app.books.open('./examle.xlsx')
worksheet = workbook.sheets['sheet1']
worksheet.api.PrintOut(Copies=2,ActivePrinter='DESKTOP-HP01',Collate=True)
wrokbook.save()
workbook.close()
app.quit()
3.3.3 Zoom属性–调整工作表的打印缩放比例
表达式.api.PageSetup.Zoom
- Zoom属性的取值范围为10400,代表10%400%的打印缩放比例
import xlwings as xw
app = xw.App(visible=Flase, add_book=Flase)
workbook = app.books.open('./examle.xlsx')
worksheet = workbook.sheets['sheet1']
worksheet.api.PageSetup.Zoom = 50
worksheet.api.PrintOut(Copies=2,ActivePrinter='DESKTOP-HP01',Collate=True)
wrokbook.save()
workbook.close()
app.quit()
3.3.4 CenterHorizontally属性和CenterVertically属性–设置工作表的打印位置
import xlwings as xw
app = xw.App(visible=Flase, add_book=Flase)
workbook = app.books.open('./examle.xlsx')
worksheet = workbook.sheets['sheet1']
worksheet.api.PageSetup.CenterHorizontally = True
# 打印所选工作表时让打印内容在页面的水平方向上整体居中
worksheet.api.PageSetup.CenterVertically= True
# 打印所选工作表时让打印内容在页面的垂直方向上整体居中
worksheet.api.PrintOut(Copies=2,ActivePrinter='DESKTOP-HP01',Collate=True)
wrokbook.save()
workbook.close()
app.quit()
3.3.5 PrintHeadings属性–打印工作表时打印行号和列标
import xlwings as xw
app = xw.App(visible=Flase, add_book=Flase)
workbook = app.books.open('./examle.xlsx')
worksheet = workbook.sheets['sheet1']
worksheet.api.PageSetup.PrintHeadings = True
# 设置打印所选工作表时打印行号和列标
worksheet.api.PrintOut(Copies=2,ActivePrinter='DESKTOP-HP01',Collate=True)
wrokbook.save()
workbook.close()
app.quit()
3.3.6 Color属性–设置工作表的标签颜色
表达式.api.Tab.Color
- Color属性的颜色值是一个整数,而我们常用的颜色值时RGB值,两者的换算公式为:
- Color属性值=R+G256+B256*256
- 同时也可以直接使用xlwings的utils子模块的rgb_to_int()函数来完成转换
import xlwings as xw
app = xw.App(visible=Flase, add_book=Flase)
workbook = app.books.open('./examle.xlsx')
worksheet = workbook.sheets['sheet1']
worksheet.api.Tab.Color= xw.utils.rgv_to_int((255,0,0))
# 设置所选工作表的标签颜色
wrokbook.save()
workbook.close()
app.quit()