python - 使用 Win32com 从 Python 中处理 Excel 消息框

标签 python excel messagebox win32com

我正在尝试处理一些应该是 xls 文件的文件,但事实证明它们是别的东西(根据我在 python-excel 板上收到的一些帮助,这些是 Web 存档文件或(单文件网页(*.mht , *.mhtml) )。我可以使用 Excel 打开文件,但我收到一条消息,必须先关闭才能继续前进。消息是 - 您尝试打开的文件 filename.xls 的格式不同于由文件扩展名指定。在打开文件之前,请确认文件没有损坏并且来自受信任的来源。要打开文件吗?

如果我点击是,该文件将打开,它看起来像一个 Excel 工作簿。某些工作表名称被截断。果然,当我点击“另存为”时,显示的默认格式是单个文件网页。

现在,如果我另存为并选择 excel 97-2003 格式,重命名为我的新名称并点击“保存”按钮,然后文件将使用 Excel 打开,以后没有问题。

我一直在试图弄清楚如何编写一些代码来打开并将它们保存为真正的 xls 文件,这样我就不必让某人在海外打开并保存它们。

我已经非常接近但被困在最后一个问题上,当我用新的文件格式保存它时,我收到一个警告框,警告我会有一些轻微的保真度损失。我不知道如何抑制它并接受失去保真度?

这是看起来有效的拼凑在一起的部分

import win32com.client
xl=win32com.client.Dispatch('Excel.Application')
xl.visible=0  # I have noticed that if I don't set visible to 0 I can't get any response
srce=xl.Workbooks.Open(r'c:\testdd.xls') # testdd is my file that is evidently really not an excel file
srce.SaveAs(r'c:\newtttxt2.xls',FileFormat=1)  # this is when the message box pops up

我找到了对名为 CheckCompatibility 的属性的引用。它似乎是工作簿对象的属性。而且我想我不能以表格的形式使用它
srce.CheckCompatibility='False' 

是因为我没有保存 srce 对象,而是保存了它的某种类型的副本?

回到矿山。

错误希望我在尝试 srce.CheckCompatibility='False' 时没有成功

抱歉有任何困惑

好吧,现在我比平时更困惑这种行为很奇怪
srce=xl.Workbooks.Open(r'c:\testdd.xls') # I open the file
srce.CheckCompatibility='False' # I try to assign the attribute to srce

srce.SaveAs(r'c:\newtttxt7865.xls',FileFormat=1)  #when I SaveAs the compatibility dialog asks if I want to continue
>>> 'asked'  # I put this here to reinforce the fact that  I was asked
'asked'
>>> srce.CheckCompatibility='False'    # again I try to assign the attribute 
>>> srce.SaveAs(r'c:\newtttxt78653.xls',FileFormat=1)   # I try to save it again
>>> 'did not ask'                                       #it saves this time w/o asking
'did not ask'
>>> 

我想知道我是否按照 com 帮助中的描述添加了一个 make.py 文件,如果这会得到解决?我开始怀疑问题是否在于 srce 还不知道它有什么属性,它接受了分配,但直到某些情况发生才开始发挥作用?如果我听起来很愚蠢,那也没关系。

最佳答案

请看我对 your other question on this issue. 的回答

第二次调用 SaveAs(...) 时没有显示对话框的原因是文件格式在第二次调用时没有改变,文件格式只在第一次调用时改变。

你想要的是添加

>>> xl.DisplayAlerts = False

在调用 SaveAs() 之前.

关于python - 使用 Win32com 从 Python 中处理 Excel 消息框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5207955/

相关文章:

VBA如果范围1中的值然后范围2中的值乘以-1

vba - Excel VBA从excel修改word doc - 集合成员错误

python - Fabric 命名空间需要一个 fabfile

python - TypeError : Improper input: N=3 must not exceed M=1, 不确定我的尺寸有什么问题?

Python正则表达式: search from right to left by delimiter,然后在分隔符左侧部分从右向左搜索

Delphi消息框出现在其他窗体后面

消息框上的图像/图片 C#

python - 如何从 Python 中的名称和类列表实例化许多不同的类

vba - 查找重复值并移动到不同的工作表

c# - 如何在 WinForms 中显示包含详细信息的消息框?