Skip to content Skip to sidebar Skip to footer

How To Give Range Of A Worksheet As Variable

I am having one excel sheet which is used to read the data through python openpyxl...so in my script i have values that are hard coded as ws['E2':'AB3'] as AB3 is the last entry to

Solution 1:

Question: how can i make the code generic

Note: I assume you always want to start at 'E2'.

from openpyxl.utils import range_boundaries
# Defineonlystart'E2',     
# all max_*values, lastRow, Column, are returned byDefault
min_col, min_row, max_col, max_row = range_boundaries('E2')

# Iterate allRows, starting at min_row ==2for columns in worksheet.iter_rows(min_col=min_col, min_row=min_row, max_col=max_col, max_row=max_row):
    # Iterate all Columns, starting at min_col =='E'for cell in columns:
        print('%s: cell.value=%s'% (cell, cell.value) )  

Solution 2:

If you just want to load all of the columns, use pandas, its simpler and has much more functionality.

import pandas as pd

# Load in the Excel file (sheetname is optional, defaults to first sheet)
df = pd.read_excel('/some/file/path/excel_file_name.xlsx', sheetname='Sheetx')

# Check the first 5 rowsprint(df.head())

Post a Comment for "How To Give Range Of A Worksheet As Variable"