Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: openpyxl change cell fill to 'none' and borders to 'none'

Tags:

python

excel

I've got an Excel document that I'm trying to remove formatting (any cell coloring / borders) on 2 sheets; 'Table' & 'Test'.

I've looked through all the documentation on PatternFill, but I only see how to apply colors/formatting and not how to reset them to null.

Any help/advice you all could provide would be greatly appreciated.

Thanks

like image 709
Steve Wolfe Avatar asked Oct 30 '17 17:10

Steve Wolfe


1 Answers

A PatternFill object with argument fill_type=None has to be created in order to get no cell color. Below is a code snippet for stripping all cells in an existing excel workbook of color and borders:

import openpyxl

# Load workbook
wb = openpyxl.load_workbook('workbook.xlsx')

# Initialize formatting styles
no_fill = openpyxl.styles.PatternFill(fill_type=None)
side = openpyxl.styles.Side(border_style=None)
no_border = openpyxl.styles.borders.Border(
    left=side, 
    right=side, 
    top=side, 
    bottom=side,
)

# Loop through all cells in all worksheets
for sheet in wb.worksheets:
    for row in sheet:
        for cell in row:
            # Apply colorless and borderless styles
            cell.fill = no_fill
            cell.border = no_border

# Save workbook
wb.save('workbook_modified.xlsx')
like image 81
Xukrao Avatar answered Nov 14 '22 21:11

Xukrao