如何使用Python打开Excel文件以显示其内容? [英] How to open an Excel file with Python to display its content?

查看:1568
本文介绍了如何使用Python打开Excel文件以显示其内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我正在尝试使用Python打开一个excel文件,以显示所收录的数据,就像我们用鼠标双击一样。有一段时间,但似乎所有的页面都在谈论如何使用代码读写Excel文件,而不是向用户显示内容。



所以,是有什么解决方案我的问题?



非常感谢。

解决方案

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

  import os 
file =C:\\ \\\Documents\\file.txt
os.startfile(file)

这将打开与文件扩展名相关联的任何应用程序的文件。



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

 >>>导入psutil 
>>>导入子流程
>>>> doc = subprocess.Popen([start,/ WAIT,file.pdf],shell = True)#将打开的文件作为doc
>>> doc.poll()#显示该进程仍然存在(如果/ WAIT参数从上一行中排除,则返回0)
>>> psutil.Process(doc.pid).get_children()[0] .kill()#处理过程
>>> doc.poll()#显示进程已被杀死
0
>>>

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


I am trying to open an excel file with Python to display the data that contented in it, just like we double click it with mouse.

I've search for a while, but seems all the pages are talking about how to read and write an excel file with code, rather than display the content to the user.

So, is there any solution for my problem?

Thanks a lot.

解决方案

To simply open a file in its default application, you can use

import os
file = "C:\\Documents\\file.txt"
os.startfile(file)

This will open the file in whatever application is associated with the file extension.

There are some drawbacks however, so if you want to do some more advanced handling of the file (such as closing it later), you need a more advanced approach. You can try the solution to my question here which shows how to use subprocess.popen() to keep track of the file, and then close it. Here's the general idea:

>>> 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
>>> 

This retains the file you opened as the doc object so that it can be easily closed later

这篇关于如何使用Python打开Excel文件以显示其内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆