Python 使用 xlwt 'get_sheet' 方法访问工作表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14587271/
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-18 11:54:09  来源:igfitidea点击:

Accessing worksheets using xlwt 'get_sheet' method

pythonxlrdxlwtxlutils

提问by user2001139

I would like to access worksheets of a spreadsheet. I've copied the main workbook to another workbook using xlutils.copy(). But don't know the right way to access worksheets using xlwt module. My sample code:

我想访问电子表格的工作表。我已使用 xlutils.copy() 将主工作簿复制到另一个工作簿。但是不知道使用 xlwt 模块访问工作表的正确方法。我的示例代码:

import xlrd
import xlwt
from xlutils.copy import copy

wb1 = xlrd.open_workbook('workbook1.xls', formatting_info=True)
wb2 = copy(master_wb)

worksheet_name = 'XYZ' (worksheet_name is a iterative parameter)

worksheet = wb2.get_sheet(worksheet_name)

Could someone please tell me what's the right command line to access the existing worksheets in a workbook using xlwt module? I know we can use 'add_sheet' method to add a worksheet in the existing workbook using xlwt module.

有人可以告诉我使用 xlwt 模块访问工作簿中现有工作表的正确命令行是什么吗?我知道我们可以使用 'add_sheet' 方法使用 xlwt 模块在现有工作簿中添加工作表。

Any help, appreciated.

任何帮助,不胜感激。

回答by user2100379

You can do sheets = wb1.sheets()to get a list of sheet objects, then call .nameon each to get their names. To find the index of your sheet, use

您可以sheets = wb1.sheets()获取工作表对象的列表,然后调用.name每个对象以获取它们的名称。要查找工作表的索引,请使用

[s.name for s in sheets].index(sheetname)

回答by dhdaines

The sheets()method is curiously absent from the xlwt.Workbookclass, so the other answer using that method will not work - only xlrd.book(for reading XLS files) has a sheets()method. Because all the class attributes are private, you have to do something like this:

类中sheets()奇怪地没有该方法xlwt.Workbook,因此使用该方法的另一个答案将不起作用 - 只有xlrd.book(用于读取 XLS 文件)有一个sheets()方法。因为所有的类属性都是私有的,所以你必须做这样的事情:

def get_sheet_by_name(book, name):
    """Get a sheet by name from xlwt.Workbook, a strangely missing method.
    Returns None if no sheet with the given name is present.
    """
    # Note, we have to use exceptions for flow control because the
    # xlwt API is broken and gives us no other choice.
    try:
        for idx in itertools.count():
            sheet = book.get_sheet(idx)
            if sheet.name == name:
                return sheet
    except IndexError:
        return None

If you don't need it to return None for a non-existent sheet then just remove the try/except block. If you want to access multiple sheets by name repeatedly it would be more efficient to put them in a dictionary, like this:

如果您不需要它为不存在的工作表返回 None ,那么只需删除 try/except 块。如果您想按名称重复访问多个工作表,将它们放入字典中会更有效,如下所示:

sheets = {}
try:
    for idx in itertools.count():
        sheet = book.get_sheet(idx)
        sheets[sheet.name] = sheet
except IndexError:
        pass

回答by Sharath K

Well, here is my answer. Let me take it step-by-step. Considerting previous answers, xlrd is the right module to get the worksheets.

嗯,这是我的答案。让我一步一步来。考虑到以前的答案,xlrd 是获取工作表的正确模块。

  1. xlrd.Book object is returned by open_workbook.

    rb = open_workbook('sampleXLS.xls',formatting_info=True)

  2. nsheetsis an attribute integer which returns the total number of sheets in the workbook.

    numberOfSheets=rb.nsheets

  3. Since you have copied this to a new workbook wb-> basically to write things, wb to modify excel wb = copy(rb)

  4. there are two ways to get the sheet information,

    a.if you just want to read the sheets, use sheet=rb.sheet_by_index(sheetNumber)

    b.if you want to edit the sheet, use ws = wb.get_sheet(sheetNumber)(this is required in this context to the asked question)

  1. xlrd.Book 对象由 open_workbook 返回。

    rb = open_workbook('sampleXLS.xls',formatting_info=True)

  2. nsheets是一个属性整数,它返回工作簿中的工作表总数。

    numberOfSheets=rb.nsheets

  3. 既然你已经把它复制到一个新的工作簿wb-> 基本上是为了写东西,wb 来修改 excel wb = copy(rb)

  4. 有两种方法可以获取工作表信息,

    一种。如果您只想阅读工作表,请使用sheet=rb.sheet_by_index(sheetNumber)

    如果您想编辑工作表,请使用ws = wb.get_sheet(sheetNumber)(在此上下文中对所提出的问题是必需的)

you know how many number of sheets in excel workbook now and how to get them individually, putting all of them together,

您现在知道excel工作簿中有多少张工作表以及如何单独获取它们,将它们放在一起,

Sample Code:

示例代码:

reference: http://www.simplistix.co.uk/presentations/python-excel.pdf

参考:http: //www.simplistix.co.uk/presentations/python-excel.pdf

from xlrd import open_workbook
from xlutils.copy import copy
from xlwt import Workbook

rb = open_workbook('sampleXLS.xls',formatting_info=True)
numberOfSheets=rb.nsheets
wb = copy(rb)

for each in range(sheetsCount):
    sheet=rb.sheet_by_index(each)
    ws = wb.get_sheet(each)
    ## both prints will give you the same thing
    print sheet.name
    print ws.name