Apply borders to all cells in a range with openpyxl

后端 未结 8 747
面向向阳花
面向向阳花 2021-01-03 01:28

I have a script that takes a pandas dataframe and chops it up into several hundred chunks and saves each chunk as a separate excel file. Each chunk will have the same number

相关标签:
8条回答
  • 2021-01-03 02:04

    seems there is no built-in for this task, and we have to make some steps ourselves, like:

    #need make conversion from alphabet to number due to range function
    def A2N(s,e):
        return range(ord(s), ord(e)+1)
    #B1 is the border you defined
    #Assume you trying border A1-Q1 ... A3-Q3
    X = A2N('A','Q')
    #print X    
    your_desired_sheet_range_rows = range(1,4)
    #need two loop to go through cells
    for row in your_desired_sheet_rows:
        for col in X:
            ca = chr(col)
            sheet[ca+str(row)].border=B1
    
    0 讨论(0)
  • 2021-01-03 02:07

    Decision that works on openpyxl 2.3.5

    from openpyxl.styles import Border, Side
    
    def set_border(ws, cell_range):
        border = Border(left=Side(border_style='thin', color='000000'),
                    right=Side(border_style='thin', color='000000'),
                    top=Side(border_style='thin', color='000000'),
                    bottom=Side(border_style='thin', color='000000'))
    
        rows = ws.iter_rows(cell_range)
        for row in rows:
            for cell in row:
                cell.border = border
    
    set_border(worksheet, 'A5:C10')
    
    0 讨论(0)
提交回复
热议问题