Apply Border To Range Of Cells Using Openpyxl

2024/11/15 14:59:33

I am using python 2.7.10 and openpyxl 2.3.2 and I am a Python newbie.

I am attempting to apply a border to a specified range of cells in an Excel worksheet (e.g. C3:H10). My attempt below is failing with the the following message:

AttributeError: 'Cell' object has no attribute 'styles'.

How do I attach a border to a cell? Any insights would be gratefully received.

My current code:

import openpyxl
from openpyxl.styles import Border, Sidedef set_border(ws, cell_range):rows = ws.iter_rows(cell_range)for row in rows:row[0].styles.borders = Border(left=Side(border_style='thin', color="FF000000"))row[-1].styles.borders = Border(right=Side(border_style='thin', color="FF000000"))for c in rows[0]:c.styles.borders = Border(top=Side(border_style='thin', color="FF000000"))for c in rows[-1]:c.styles.borders = Border(bottom=Side(border_style='thin', color="FF000000"))# Example call to set_border
wb = openpyxl.load_workbook('example.xlsx')
ws = wb.get_sheet_by_name('Sheet1')set_border(ws, "B3:H10")
Answer

First of all properties are called style (not styles) and border (not borders). Also to change border you should set cell.border directly.

Besides that you have some problems with borders logic, it's more complex to get it working correctly, because of iterators and corners. Here is a rough version (it is as simple as I could get it, but not memory efficient):

def set_border(ws, cell_range):rows = ws[cell_range]side = Side(border_style='thin', color="FF000000")rows = list(rows)  # we convert iterator to list for simplicity, but it's not memory efficient solutionmax_y = len(rows) - 1  # index of the last rowfor pos_y, cells in enumerate(rows):max_x = len(cells) - 1  # index of the last cellfor pos_x, cell in enumerate(cells):border = Border(left=cell.border.left,right=cell.border.right,top=cell.border.top,bottom=cell.border.bottom)if pos_x == 0:border.left = sideif pos_x == max_x:border.right = sideif pos_y == 0:border.top = sideif pos_y == max_y:border.bottom = side# set new border only if it's one of the edge cellsif pos_x == 0 or pos_x == max_x or pos_y == 0 or pos_y == max_y:cell.border = border
https://en.xdnf.cn/q/71876.html

Related Q&A

Make a functional field editable in Openerp?

How to make functional field editable in Openerp?When we createcapname: fields.function(_convert_capital, string=Display Name, type=char, store=True ),This will be displayed has read-only and we cant …

how to read a fasta file in python?

Im trying to read a FASTA file and then find specific motif(string) and print out the sequence and number of times it occurs. A FASTA file is just series of sequences(strings) that starts with a header…

Passing a pandas dataframe column to an NLTK tokenizer

I have a pandas dataframe raw_df with 2 columns, ID and sentences. I need to convert each sentence to a string. The code below produces no errors and says datatype of rule is "object." raw_d…

SWIG - Wrap C string array to python list

I was wondering what is the correct way to wrap an array of strings in C to a Python list using SWIG.The array is inside a struct :typedef struct {char** my_array;char* some_string; }Foo;SWIG automati…

How to show an Image with pillow and update it?

I want to show an image recreated from an img-vector, everything fine. now I edit the Vector and want to show the new image, and that multiple times per second. My actual code open tons of windows, wit…

How do I map Alt Gr key combinations in vim?

Suppose I wanted to map the command :!python % <ENTER> to pressing the keys Alt Gr and j together?

cannot import name get_user_model

I use django-registrations and while I add this code in my admin.pyfrom django.contrib import adminfrom customer.models import Customerfrom .models import UserProfilefrom django.contrib.auth.admin impo…

pytest: Best Way To Add Long Test Description in the Report

By default pytest use test function names or test files names in pytest reportsis there any Best way to add test description (Long test name) in the report with out renaming the files or functions usin…

Adding a calculated column to pandas dataframe

I am completely new to Python, pandas and programming in general, and I cannot figure out the following:I have accessed a database with the help of pandas and I have put the data from the query into a …

Scipy: Centroid of convex hull

how can I calculate the centroid of a convex hull using python and scipy? All I found are methods for computing Area and Volume.regards,frank.