如何用Python打开Excel文件来显示其内容?

Cha*_*ame 3 python excel

我正在尝试用Python打开一个excel文件来显示满足其中的数据,就像我们用鼠标双击它一样.

我已经搜索了一段时间,但似乎所有页面都在谈论如何使用代码读取和编写excel文件,而不是向用户显示内容.

那么,我的问题有什么解决方案吗?

非常感谢.

wnn*_*maw 18

要在其默认应用程序中简单地打开文件,您可以使用

import os
file = "C:\\Documents\\file.txt"
os.startfile(file)
Run Code Online (Sandbox Code Playgroud)

这将在与文件扩展名关联的任何应用程序中打开该文件.

但是有一些缺点,因此如果您想对文件进行更高级的处理(例如稍后关闭),则需要更高级的方法.您可以在此处尝试我的问题的解决方案,其中显示了如何使用subprocess.popen()来跟踪文件,然后关闭它.这是一般的想法:

>>> import psutil
>>> import subprocess
>>> doc = subprocess.Popen(["start", "/WAIT", "file.pdf"], shell=True)   #Stores the open file as doc
>>> doc.poll()                                                           #Shows that the process still exists (will return 0 if the /WAIT argument is excluded from previous line)
>>> psutil.Process(doc.pid).get_children()[0].kill()                     #Kills the process
>>> doc.poll()                                                           #Shows that the process has been killed
0
>>> 
Run Code Online (Sandbox Code Playgroud)

这将保留您作为doc对象打开的文件,以便以后可以轻松关闭

  • RE:原始字符串-反斜杠仍将转义引号字符(“或'),因此您无法执行`r” C:\ files \ go \ here \ but \ end \ in \ a \ slash \“- -它会在扫描字符串文字时给您“ SyntaxError:EOL” (2认同)