Python Forum

Full Version: Python - Merge existing cells of Excel file created with xlsxwriter
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,
I'm writing a Python script which creates an Excel file. The worksheet that causes me problems is the one with a calendar of each month. I would like to have the week number above the days of each week. I already generated that, but I would like to merge the week number cells.

Does anyone know if there is a fonction for that ?

Here is the code that generates the worksheet.
import xlsxwriter
import calendar 
import datetime
import time
import locale
import pandas as pd


def calendrier(year,mnth):
    cal= calendar.Calendar()
    temp=cal.monthdatescalendar(year, mnth)
    datesMois=[]
    for w in temp:
        for d in w:
            if d.month==mnth:
                datesMois.append(d)
    
    locale.setlocale(locale.LC_ALL, "")
    nomMois=datetime.datetime.strptime(str(mnth), "%m").strftime("%B")
    
    #locale.setlocale(locale.getdefaultlocale())
       
    return datesMois,nomMois


annee=2021
for m in range(1,13):
    exec("dates"+str(m)+",nom"+str(m)+"=calendrier(annee,m)")
    
workbook = xlsxwriter.Workbook('essai.xlsx')

merge_format = workbook.add_format({   # format jours de la semaine
    'align': 'center',
    'bold': 1,
    'valign': 'vcenter'})
date_format=workbook.add_format({      # format date
    'align': 'center',
    'bold': 1,
    'num_format':'dd/mm/yy',
    'valign': 'vcenter'})
date_formatTDB=workbook.add_format({   # format Date dans le tableau de bord (format minimaliste)
    'align': 'center',
    'num_format':'dd',
    'valign': 'vcenter'})


# ajout de la feuille "Tableau de bord"
tdb=workbook.add_worksheet('Tableau de bord')


l=1
for m in range(1,13):
    # dd=1
    # ld=[]
    # exec("for d in dates"+str(m)+":\n\tif d.strftime('%a')=='dim.':\n\t\tld.append(dd+1)\n\tdd+=1")
    # print(ld)
    # exec("tdb.merge_range('B"+str(l)+":Z"+str(l)+"', nom"+str(m)+", merge_format)")
    # exec("tdb.merge_range(l,ld[0],l,ld[1],dates"+str(m)+"[ld[1]].strftime('%V'),merge_format)")
    exec("for cmp in range(1,len(dates"+str(m)+")+1):\n\ttdb.write(l,cmp, dates"+str(m)+"[cmp-1].strftime('%V'), date_formatTDB)")
    # exec("for j in range(1,len(ld)-1):\n\tprint(j)\n\ttdb.merge_range(l,ld[j],l,ld[j+1],dates"+str(m)+"[ld[j]].strftime('%V'),merge_format)")
    exec("for cmp in range(1,len(dates"+str(m)+")+1):\n\ttdb.write(l+1,cmp, dates"+str(m)+"[cmp-1].strftime('%a'), date_formatTDB)")
    exec("for cmp in range(1,len(dates"+str(m)+")+1):\n\ttdb.write(l+2,cmp, dates"+str(m)+"[cmp-1], date_formatTDB)")
    l+=22
    
    
workbook.close()
Thanks in advance,
Manon