Python Forum

Full Version: Changing the initial worksheet name in an MS Excel file
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
In the following code I want the initial sheet name to change from 'Sheet' to some other name. What code can I use to do this. Is there a way of making the initial sheet to a nane other than 'Sheet' from the beginning without even changing it afterwards?

from openpyxl import Workbook

# This function will create a default MS Excel file.  
def create_excel_file(excel_file_name):

    # creates Workbook object.
    wb = Workbook()

    # invoke Workbook.active property to create the initial worksheet i.e. ‘Sheet’
    initial_work_sheet = wb.active

    # workbook has an initial worksheet.
    initial_sheet_names = wb.sheetnames
    print(initial_sheet_names)
It's OK folks I worked it out.

initial_work_sheet.title ="New_Name"
Just use sheet.title = 'a name for my sheet'

from openpyxl import Workbook
path2XL = '/home/pedro/myPython/openpyxl/xlsx_files/'
# This function will create a default MS Excel file.  
def create_excel_file(excel_file_name): 
    # creates Workbook object.
    wb = Workbook() 
    # invoke Workbook.active property to create the initial worksheet i.e. ‘Sheet’
    initial_work_sheet = wb.active
    initial_work_sheet.title = 'my shiny new sheet'
    # workbook has an initial worksheet.
    initial_sheet_names = wb.sheetnames    
    print(initial_sheet_names)
    sheet = initial_sheet_names[0]
    # make sure you can write to it
    for colNum in range(1, 5):
        wb[sheet].cell(row=1, column=colNum).value='some data'
    wb.save(path2XL + 'shiny_newXL.xlsx')
Many thanks Pedroski55.