Python XLRD 使用范围

Python XLRD use Range

我想将 excel 范围分配给变量:

import xlrd

file = r"C:\Users\Lisa\Desktop\Frank\export.XLSX"
book = xlrd.open_workbook(file)
sheet = book.sheet_by_index(0)
data = [range("A3:D7")]

,但出现错误:

    data = [range("A3:D7")]
TypeError: 'str' object cannot be interpreted as an integer

有什么想法吗?

您可以使用以下方法从 XLSX 文件中提取块,如下所示:

import xlrd

workbook = xlrd.open_workbook(r"input.xlsx")
sheet = workbook.sheet_by_index(0)

def get_cell_range(start_col, start_row, end_col, end_row):
    return [sheet.row_slice(row, start_colx=start_col, end_colx=end_col+1) for row in xrange(start_row, end_row+1)]

data = get_cell_range(0, 2, 3, 6)   # A3 to D7
print data

xlrd 使用从 0 开始的列号和行号而不是 Excel 单元格名称。它只能使用 xlrd.cellname() 将 Excel 单元格引用从 col 行格式转换为 A1 格式,而不是相反。

我也遇到了同样的问题。然后我就这样解决了。

首先我为xlrd.cellname()创建了一个反函数,然后我继续执行该函数以获取范围

的值
import xlrd
import re

def parse_cell(cell):
    r = re.compile("([a-zA-Z]+)([0-9]+)")
    m = r.match(cell)
    col = m.group(1).upper()
    number_row = int(m.group(2)) - 1

    ABC = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]

    number_col = 0
    for char in col:
        number_col += ABC.index(char)

    return (number_row, number_col)


def get_cell_range_values(sheet, start_cell, end_cell):
    start_cell_parsed = parse_cell(start_cell)
    end_cell_parsed = parse_cell(end_cell)

    data = sheet.col_values(start_rowx=start_cell_parsed[0], colx=start_cell_parsed[1], end_rowx=end_cell_parsed[0] + 1)
    return data


file = r"C:\Users\Lisa\Desktop\Frank\export.XLSX"
book = xlrd.open_workbook(file)
sheet = book.sheet_by_index(0)
data = get_cell_range_values(sheet, "A3", "A130")

请记住,您只能得到线性范围,不要创建矩阵