首页 > 解决方案 > 如何在 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’”

我希望有人可以在这件事上帮助我 - 提前谢谢。

标签: pythonexcel

解决方案


尝试

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


推荐阅读