使用xlwt'get_sheet'方法访问工作表 [英] Accessing worksheets using xlwt 'get_sheet' method

查看:1370
本文介绍了使用xlwt'get_sheet'方法访问工作表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:

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模块访问工作簿中现有工作表的正确命令行是什么吗?我知道我们可以使用xlwt模块使用'add_sheet'方法在现有工作簿中添加工作表.

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.Workbook类奇怪地缺少sheets()方法,因此使用该方法的其他答案将不起作用-仅xlrd.book(用于阅读) XLS文件)具有sheets()方法.因为所有的类属性都是私有的,所以您必须执行以下操作:

The sheets() method is curiously absent from the xlwt.Workbook class, 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:

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块.如果要按名称重复访问多个工作表,将它们放入字典中会更有效,例如:

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:

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

这篇关于使用xlwt'get_sheet'方法访问工作表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆