从EXCEL获取列表的Get_Squared_Range

2022-04-07 00:00:00 python excel openpyxl readfile

问题描述

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)的矩阵


解决方案

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()Do:

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]

相关文章