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



我想访问电子表格的工作表。我已经使用 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)

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

任何帮助,非常感谢。

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

[s.name for s in sheets].index(sheetname)
奇怪的是,

xlwt.Workbook类中没有sheets()方法,因此使用该方法的另一个答案将不起作用 - 只有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

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

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

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

  1. XLRD。书籍对象由open_workbook返回。

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

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

    numberOfSheets=rb.nsheets

  3. 由于您已将其复制到新的工作簿wb ->基本上是为了写东西,wb 修改 excel wb = copy(rb)

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

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

    b. 如果要编辑工作表,请使用ws = wb.get_sheet(sheetNumber)(在这种情况下,这是所问问题所必需的)

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

示例代码:

参考: 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

最新更新