Home > Net >  Store cell value of first few characters
Store cell value of first few characters

Time:10-25

I am trying to change the name of a sheet according to the value of a cell.

here is the code I am using.


from openpyxl import load_workbook

wb = load_workbook('file_name.xlsx') 
ws = wb['Sheet 1']
sheet_name = ws['B2']
ws.title = f'Marketing {sheet_name}'

This code works, but my problem is I only need to extract the first 3 characters from the cell ws['B2']. How can I do that.

CodePudding user response:

Use slicing:

sheet_name = ws['B2'].value[:3]

CodePudding user response:

You can use the characters in the string.

Edit the parameters to get the desired result.

from openpyxl import load_workbook

wb = load_workbook('file_name.xlsx') 
ws = wb['Sheet 1']
sheet_name = ws['B2'].value
ws.title = f'Marketing {sheet_name[0:3]}'  # First character to third

Start reading the tabs by number so you don't have to change the tab name in the future.

Final code:

from openpyxl import load_workbook

wb = load_workbook('file_name.xlsx') 
ws = wb.worksheets[0] # First tab
sheet_name = ws['B2'].value
ws.title = f'Marketing {sheet_name[0:3]}' # First character to third
  • Related