-2

I want to write a script that can get json from the backend to create an xlsx file, but I'm stuck here. The problem is that the text that is in this

Cell crosses the boundaries. It should be like this.

Md. Yeasin Sheikh
  • 54,221
  • 7
  • 29
  • 56
oneku
  • 9
  • 4
  • Please include your own code and information in the question and avoid links to images. – Charlie Clark Jul 14 '22 at 09:14
  • If openpyxl is not a must and you are running on Windows with Excel you can format the cell as your example including setting the 'Room' text to a different color [Red] using Xlwings. – moken Jul 17 '22 at 03:39

1 Answers1

0

You can use the below code to do what you require using openpyxl. The exception is that you cannot have multiple colors within the same cell (just one color, not multiple colors). To do that, you will need to use xlsxwriter, but that will work only on sheets written with xlsxwriter. More information is available here.

Code

import openpyxl
from openpyxl.styles import Color, PatternFill, Font, Border, Alignment, Side

### Your merged cell is in Sheet1 > D3:E6 ###
wb=openpyxl.load_workbook('yourfile.xlsx')
ws=wb['Sheet1']

#Background color change
yellowFill = PatternFill(start_color='FFFF00', end_color='FFFF00', fill_type='solid')
ws['D3'].fill = yellowFill

#Cell text alignment change
ws['D3'].alignment = Alignment(wrap_text=True, horizontal='center', vertical='center')

#Font style, size, bold and color (black, but you can change
col_style = Font(name = "Calibri", size = 12, color = "000000", bold =True)
ws['D3'].font = col_style

#Border for the merged cell - it is thin black, but you can change
def set_border(ws, cell_range):
    thin = Side(border_style="thin", color="000000")
    for row in ws[cell_range]:
        for cell in row:
            cell.border = Border(top=thin, left=thin, right=thin, bottom=thin)

set_border(ws, 'D3:E6') 

wb.save('output.xlsx')

enter image description here

Redox
  • 9,321
  • 5
  • 9
  • 26