Openpyxl - How to read only one column from Excel file in Python?

后端 未结 8 1159
-上瘾入骨i
-上瘾入骨i 2020-12-14 18:14

I want to pull only column A from my spreadsheet. I have the below code, but it pulls from all columns.

from openpyxl import Workbook, load_workbook

wb=load         


        
相关标签:
8条回答
  • 2020-12-14 19:18

    Using openpyxl

    from openpyxl import load_workbook
    # The source xlsx file is named as source.xlsx
    wb=load_workbook("source.xlsx")
    
    ws = wb.active
    first_column = ws['A']
    
    # Print the contents
    for x in xrange(len(first_column)): 
        print(first_column[x].value) 
    
    0 讨论(0)
  • 2020-12-14 19:18

    Using ZLNK's excellent response, I created this function that uses list comprehension to achieve the same result in a single line:

    def read_column(ws, begin, columns):
      return [ws["{}{}".format(column, row)].value for row in range(begin, len(ws.rows) + 1) for column in columns]
    

    You can then call it by passing a worksheet, a row to begin on and the first letter of any column you want to return:

    column_a_values = read_column(worksheet, 2, 'A')
    

    To return column A and column B, the call changes to this:

    column_ab_values = read_column(worksheet, 2, 'AB')
    
    0 讨论(0)
提交回复
热议问题