python - 如何在 Python 中从 Excel 中返回 PrintArea
问题描述
在用户选择 Excel-文件。
Excel 文件包含许多不同的页面设置设置,每个 Excel 文件中的每个工作表都有不同的页面设置。
因此,任务是我需要读取有关页面设置的所有当前变量,以便能够将它们分配给相关变量以进行导出。
问题是当我试图让 Excel 返回工作表的当前打印区域时,我无法弄清楚。据我了解,我需要能够读取当前打印区域,以便能够将其设置为导出。
Excel 文件是“.xlxs”和“.xlsm”的混合体。
我尝试使用 Excel VBA 文档中的各种不同方法,但到目前为止没有任何效果,例如添加“.Range”和“.Address”等。
我也尝试过“.UsedRange”,但我可以搜索的单元格没有显着差异,我无法以特定方式格式化它们,所以我不能使用它。
我也尝试在“ExportAsFixedFormat”函数中使用“IgnorePrintAreas = False”变量,但这也不起作用。
#This is some of the script.
#I've left out irrelevant parts (dialogboxes etc.) just to make it shorter
#Import pywin32 and open Excel and selected workbook.
import win32com.client as win32
excel = win32.gencache.EnsureDispatch("Excel.Application")
excel.Visible = False
wb = excel.Workbooks.Open(wb_path)
#Select the 1st worksheet in the workbook
#This is just used for testing
wb.Sheets([1]).Select()
#This is the line I can't get to work
ps_prar = wb.ActiveSheet.PageSetup.PrintArea
#This is just used to test if I get the print area
print(ps_prar)
#This is exporting the selected worksheet to PDF
wb.Sheets([1]).Select()
wb.ActiveSheet.ExportAsFixedFormat(0, pdf_path, Quality = 0, IncludeDocProperties = True, IgnorePrintAreas = False, OpenAfterPublish = True)
#This closes the workbook and the Excel-file (although Excel sometimes still exists in Task Manager
wb.Close()
wb = None
excel.Quit()
excel = None
如果我保留上面的代码并尝试打开一个带有小 PrintArea (A1:H8) 的测试 Excel 文件 (.xlxs),则打印功能只会给我一个空行。如果我向 .PrintArea 添加一些东西(如上所述),我会得到 2 个错误中的 1 个:
“TypeError:'str' 对象不可调用”。
或者
“ps_prar = wb.ActiveSheet.PageSetup.PrintArea.Range AttributeError:‘str’对象没有属性‘Range’”
我希望有人可以在这件事上帮助我 - 提前谢谢。
解决方案
尝试
wb = excel.Workbooks.OpenXML(wb_path)
而不是
wb = excel.Workbooks.Open(wb_path)
我的问题是德语版的 ms-office。现在可以了。在这里查看https://social.msdn.microsoft.com/Forums/de-DE/3dce9f06-2262-4e22-a8ff-5c0d83166e73/excel-api-interne-namen?forum=officede
推荐阅读
- python - 表格样式 KeyError: u"没有名为 'Table Grid' 的样式"
- java - (Java / 处理)如何在屏幕上的不同位置创建对象的多个实例?
- css - 动画提交按钮
- java - Java 的原生字符串字符集
- google-play - 为什么在通过网络安装应用程序时忽略并覆盖 playstore url 中的 utm 参数。Play.google.com?
- c# - 如何从 Lua / MoonSharp 脚本调用和等待异步 C# 方法?
- mysql - Nodejs Mysql Select Count 嵌套循环插入查询
- html - 烧瓶验证并将文件上传到网页以
- excel - Excel VBA用户窗体通过更改名称值循环组合框
- android - java.lang.IllegalStateException:SinchClient 未启动