如何从python中用excel打开excel工作表?

2024-04-26 11:28:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道我们可以使用子流程来调用和打开资源管理器中的任何文件。但是如何使用python在Microsoft excel中打开excel文件中的特定工作表呢?

我的程序结构如下:

我在python程序中从用户那里得到工作表名,我需要在excel软件中打开excel工作表。

更新:

我的代码:

import subprocess

subprocess.call("explorer <path-to-my-file>")

但这只会在excel中打开文件我希望在调用时打开文档中的特定工作表。

提前谢谢


Tags: 文件path代码用户import程序软件流程
2条回答

使用xlrd库:

import xlrd

for name, sheet_name in zip(filename, sheetnumber):
    book = xlrd.open_workbook(name)
    sheet = book.sheet_by_name(sheet_name)
    for row in range(sheet.nrows):
        for column in range(sheet.ncols):
            print row, column

如果您想在Excel中使用该文件,并使用Python在Excel中打开它,我更喜欢subprocess.Popen()而不是subprocess.Call()。

若要在特定工作表中打开文件,应先保存在选定工作表中打开的工作簿,然后再在Excel中打开它。如果您的文件是一个.xlsx文件,那么最好的Python模块是“openpyxl”(当然,在我看来)。

以下代码在我的机器中运行良好(Windows 10、MS Excel 2016和Python 3.6.3):

import openpyxl
import subprocess
filename = "<Full path to file>"
wsToOpen = "<Worksheet name>"

# Openthe xlsx file in Python
xlsx_file = openpyxl.load_workbook(strCamArq)

# List with all the worksheets in the workbook
lst_worksheets = xlsx_file.get_sheet_names()

# Change the active worksheet in the workbook
xlsx_file._active_sheet_index = lst_worksheets.index(wsToOpen)

# Save the workbook open in the chosen sheet
xlsx_file.save(filename)

#Open the workbook in MS Excel 
subprocess.Popen([filename], shell=True)

然后,在MS Excel中打开文件,文件正好位于“wsToOpen中指定的工作表中”

相关问题 更多 >