導(dǎo)入模塊
import win32com.client
import win32con
設(shè)置打印區(qū)域
worksheet.PageSetup.PrintArea = '$A$1:$C$24'
設(shè)置頂端標(biāo)題行
worksheet.PageSetup.PrintTitleRows = '$1:$1'
設(shè)置左側(cè)標(biāo)題列
worksheet.PageSetup.PrintTitleColumns = '$A:$A'
設(shè)置文件方向
- 橫向:win32con.DMORIENT_LANDSCAPE
- 縱向: win32con.DMORIENT_PORTRAIT
worksheet.PageSetup.Orientation = win32con.DMORIENT_LANDSCAPE # 橫向
設(shè)置縮放比例(這邊不需要填%)
worksheet.PageSetup.Zoom = 80
設(shè)置N頁(yè)寬,N頁(yè)高
需要先把Zoom關(guān)掉,設(shè)置成False,才能設(shè)置。
worksheet.PageSetup.Zoom = False
worksheet.PageSetup.FitToPagesWide = 1
worksheet.PageSetup.FitToPagesTall =2
設(shè)置數(shù)據(jù)居中方式
- 水平居中方式:CenterHorizontally
- 垂直居中方式:CenterVertically
worksheet.PageSetup.CenterHorizontally = True
worksheet.PageSetup.CenterVertically = True
打印工作表
openpyxl可以設(shè)置打印參數(shù),但是沒(méi)有打印操作,這也是我出這篇的目的,彌補(bǔ)openpyxl的不足。
worksheet.PrintOut()
綜合實(shí)例
import win32com.client
import win32con
excelApp = win32com.client.Dispatch('Excel.Application')
excelApp.Visible = False
excelApp.DisplayAlerts = False
wb = excelApp.Workbooks.Open(r'C:\Users\12717\Desktop\test.xlsx')
ws = wb.Activesheet
ws.PageSetup.PrintArea = '$A$1:$C$24'
ws.PageSetup.PrintTitleRows = '$1:$1'
ws.PageSetup.PrintTitleColumns = '$A:$A'
ws.PageSetup.Orientation = win32con.DMORIENT_LANDSCAPE # 橫線(xiàn)
ws.PageSetup.Zoom = False
ws.PageSetup.FitToPagesWide = 1
ws.PageSetup.FitToPagesTall =2
ws.PageSetup.CenterHorizontally = True
ws.PageSetup.CenterVertically = True
wb.Save()
excelApp.Quit()