我正在尝试从 python 在打印机上启动打印,但使用 print_area。
我尝试了这段代码(来自聊天 GPT 的代码),但它不起作用。打印机打印整张纸,而不是我定义的打印区域。
import win32com.client
import openpyxl
def imprimer_feuille_excel(nom_fichier, nom_feuille):
# définition de la zone d'impression
wb = openpyxl.load_workbook(nom_fichier)
feuille = wb[nom_feuille]
feuille.print_area = 'A1:J10'
wb.save(nom_fichier)
#impression
excel = win32com.client.Dispatch("Excel.Application")
excel.Visible = False # Pour rendre Excel invisible pendant le processus
classeur = excel.Workbooks.Open(nom_fichier)
feuille = classeur.Sheets[nom_feuille]
feuille.PrintOut() # Imprimer la feuille
classeur.Close(SaveChanges=False) # Fermer le classeur sans sauvegarder les modifications
excel.Quit()
即使在 excel 中手动定义 print_area ,此代码也会打印整个页面(如果我可以使用 excel 中定义的 print_area 进行打印,对我来说就足够了)
感谢您的帮助
您应该能够仅使用 Xlwings 完成所有需要的操作。
既然使用 Win32com 那么 Xlwings 作为替代品应该没问题。
import xlwings as xw
xlfile = 'foo.xlsx'
sheet = 'Sheet'
with xw.App(visible=False) as app:
wb = xw.Book(xlfile) # Open workbook
ws = wb.sheets[sheet] # Open Sheet
ws.page_setup.print_area = 'A1:J10' # Set print Area
# Set page layouts if needed like fitting the print onto one page width
ws.api.PageSetup.FitToPagesWide = 1
ws.api.PrintOut(Copies=1, IgnorePrintAreas=False) # Print the page
除了其他页面设置(如果需要)之外,这就是所有必要的内容。