我需要打印一张 excel 表,并且需要使用某种 python 脚本来完成。到目前为止,我已经在我的脚本中使用了 win32com,并且我还使用以下代码完成了打印输出:
import win32com.client
o = win32com.client.Dispatch("Excel.Application")
o.Visible = 1
wb = o.Workbooks.Open(r'C:\test.xlsx')
ws = wb.Worksheets[1]
ws.PrintOut()
不幸的是,在我实际打印 excel 表之前,我需要调整此表/文件的打印设置:将格式更改为横向并更改为小/窄边距。
我发现这个站点可能包含我需要的内容:
https://msdn.microsoft.com/en-us/library/aa220363(v=office.11).aspx
不幸的是,到目前为止,我还无法更改所需的打印属性。我希望有人可以帮助我,或者至少让我朝着正确的方向前进。
最佳答案
您可以使用 PageSetup 方法 ( https://docs.microsoft.com/en-us/previous-versions/office/developer/office-2003/aa173425%28v%3doffice.11%29 ) 编辑打印设置。似乎没有您通常在 excel 应用程序中看到的窄/宽/正常边距设置,但您可以自己指定边距。
ws.PageSetup.Zoom = False
ws.PageSetup.FitToPagesTall = 1
ws.PageSetup.FitToPagesWide = 1
ws.PageSetup.PrintArea = print_area
ws.PageSetup.LeftMargin = 25
ws.PageSetup.RightMargin = 25
ws.PageSetup.TopMargin = 50
ws.PageSetup.BottomMargin = 50
wb.ExportAsFixedFormat(0, path_to_pdf)
我正在使用 ExportAsFixedFormat,但我想这也适用于 PrintOut()。
引用:Print chosen worksheets in excel files to pdf in python
编辑:
如果将 FitToPagesTall(适合一页上的所有行)和 FitToPagesWide(适合一页上的所有列)设置都设置为 True,它们将弄乱您的最终打印区域。您需要将其中至少一项指定为 False 才能使您的边距设置生效。
ws.PageSetup.FitToPagesTall = False
ws.PageSetup.FitToPagesWide = 1
关于Python:使用win32com(或其他模块)调整excel文件的打印属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46546305/