Python 从 openpyxl 获取工作表名称

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23527887/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 03:05:04  来源:igfitidea点击:

getting sheet names from openpyxl

pythonexcelopenpyxl

提问by rivu

I have a moderately large xlsx file (around 14 MB) and OpenOffice hangs trying to open it. I was trying to use openpyxlto read the content, following this tutorial. The code snippet is as follows:

我有一个中等大的 xlsx 文件(大约 14 MB),而 OpenOffice 在尝试打开它时挂起。我试图按照本教程使用openpyxl来阅读内容。代码片段如下:

 from openpyxl import load_workbook
 wb = load_workbook(filename = 'large_file.xlsx', use_iterators = True)
 ws = wb.get_sheet_by_name(name = 'big_data') 

The problem is, I don't know the sheet name, and Sheet1/Sheet2.. etc. didn't work (returned NoneType object). I could not find a documentation telling me How to get the sheet names for an xlsx files using openpyxl. Can anyone help me?

问题是,我不知道工作表名称,并且 Sheet1/Sheet2 .. 等不起作用(返回 NoneType 对象)。我找不到告诉我如何使用 openpyxl 获取 xlsx 文件的工作表名称的文档。谁能帮我?

采纳答案by alecxe

Use the sheetnamesproperty:

使用sheetnames属性

sheetnames

Returns the list of the names of worksheets in this workbook.

Names are returned in the worksheets order.

Type: list of strings

表名

返回此工作簿中工作表的名称列表。

名称按工作表顺序返回。

类型:字符串列表

print (wb.sheetnames)

You can also get worksheet objects from wb.worksheets:

您还可以从wb.worksheets以下位置获取工作表对象:

ws = wb.worksheets[0]

回答by Kamaraj

As mentioned the earlier answer you can get the list of sheet names by using the ws.sheetnames

如前所述,您可以使用 ws.sheetnames

But if you know the sheet names you can get that worksheet object by

但是,如果您知道工作表名称,则可以通过以下方式获取该工作表对象

ws.get_sheet_by_name("YOUR_SHEET_NAME")

Another way of doing this is as mentioned in earlier answer

另一种这样做的方法是在前面的答案中提到的

ws['YOUR_SHEET_NAME']

回答by ismail

python 3.xfor get sheet name you must use attribute

python 3.x获取工作表名称必须使用属性

g_sheet=wb.sheetnames

return by list

按列表返回

for i in g_sheet:
    print(i)

**shoose any name **

**选择任何名称**

ws=wb[g_sheet[0]]

or ws=wb[any name]suppose name sheet is paster

或 ws=wb[any name]假设名称表是 paste

ws=wb["paster"]