get_squared_range到excel的列表列表

时间:2017-03-01 12:40:53

标签: python excel readfile openpyxl

wb = openpyxl.load_workbook(filename = 'C:/Users/test.xlsx')
sheet = wb['sheet1']
len=sheet.max_row
vals1 = [v[0].value for v in sheet.get_squared_range(1,1,2,len)]
vals2 = [v[1].value for v in sheet.get_squared_range(1,1,2,len)]

但我想要像

那样
vals12 = [v[0].value,v[1].value for v in sheet.get_squared_range(1,1,2,len)]

其中vals12-是具有维度的矩阵(len x 2)

2 个答案:

答案 0 :(得分:3)

rows_iter = sheet.get_squared_range(1, 1, 2, sheet.max_row)
vals = [[cell.value for cell in row] for row in rows_iter]

注意:

openpyxl源代码指出已弃用get_squared_range(),您应该使用iter_rows()

    @deprecated("""
    Use ws.iter_rows() or ws.iter_cols() depending whether you
    want rows or columns returned.
    """)
[docs]    def get_squared_range(self, min_col, min_row, max_col, max_row):

使用iter_rows()执行:

rows_iter = sheet.iter_rows(min_col=1, min_row=1, max_col=2, max_row=sheet.max_row)
vals = [[cell.value for cell in row] for row in rows_iter]

答案 1 :(得分:0)

最简单的方法可能是:

values = [[cell.value for cell in col] for col in ws['A':'B']]

但您也可以在itertools.islice()

上使用ws.values