使用xlwt“get_sheet”方法访问工作表

2024-06-28 19:57:36 发布

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

我想访问电子表格的工作表。我已使用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模块在现有工作簿中添加工作表。

任何帮助,谢谢。


Tags: 模块方法代码nameimport示例sheet电子表格
3条回答

奇怪的是,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

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

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

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

  1. 打开工作簿返回xlrd.Book对象。

    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

相关问题 更多 >