使用 Python 启动 Excel 文件

Use Python to launch Excel file

当我尝试 os.system("open " + 'myfile.xlsx')
我得到输出 '0'

同样,尝试
os.system("start excel.exe myfilepath")
给出结果 32512

我已经导入 os 和系统,我正在 mac。我该如何更改它才能真正启动 excel 文件?出于好奇os,它打印出来的数字是什么意思?

谢谢!

如果您只想打开 excel 应用程序,您可以使用子进程:

import subprocess
subprocess.check_call(['open', '-a', 'Microsoft Excel'])

您还可以使用 os 并打开特定文件:

import os
os.system("open -a 'path/Microsoft Excel.app' 'path/file.xlsx'")

另一方面,如果您想要在 python 中打开一个 excel 文件并对其进行修改,则有许多包可用作 xlsxwriterxlutilsopenpyxl 我更喜欢后者。

另外请注意,如果您在 mac 上,则 excel 应用程序不是 .exe

就这两行

import os
os.system("start EXCEL.EXE file.xlsx")

前提是file.xlsx在当前目录下。

我不知道 Mac OS,但是如果 Windows 操作系统是这种情况并且正确安装了 Microsoft Windows,那么考虑使用:

import os
os.system('start "excel" "C:\path\to\myfile.xlsx"')

double-quotation 对于 excelC:\path\to\myfile.xlsx 很重要(其中 C 仅表示文件系统中分区的字母,可能会被替换为 D,E ..etc.), os.system().

中的整个字符串需要 single-quotation

在 Windows 10,这对我有用:

import os
full_path_to_file = "C:\blah\blah\filename.xlsx"
os.system(full_path_to_file)

在命令提示符下复制粘贴文件的任何完整路径(或将其传递给 os.system())似乎可以工作,只要您有权打开文件。 我想这只有在选择 Excel 作为 .xlsx 扩展的默认应用程序时才有效。

如:How to open an Excel file with Python to display its content?

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

它使用默认应用程序打开文件。