简体   繁体   中英

How do you set a border in excel up to a certain column

I am writing a dataframe to excel and trying to add borders. At the moment, I have figured out how to add the borders to the worksheet using

bold = workbook.add_format({'bold': True, 'border': True})
worksheet.set_row(1, cell_format=bold)

but this extends the border past the last column of the dataframe. Is there a way to stop the borders at the last column of my dataframe?

Thanks

I'm not sure if it's the one you're using, but this can be done with the package openpyxl .

First we can create a test dataframe:

import openpyxl
from openpyxl.styles import Border, Side
from openpyxl.utils.dataframe import dataframe_to_rows
import pandas

headers = ["column1", "column2", "column3"]
records = [{k: 0 for k in headers} for _ in range(25)]
df = pandas.DataFrame.from_records(records)

Now we create a workbook object and put the dataframe in it:

wb = openpyxl.Workbook()
ws = wb.active
for row in dataframe_to_rows(df, index=False, header=True):
    ws.append(row)

Next I define a thin border which will be used around the whole dataset

thin_border = Side(border_style="thin", color='FF000000')

Now I construct the borders required for each individual cell. You didn't specify how you would like to border the data so I assumed a border around the outside of the entire frame. Since we know the number of columns and rows we can iterate through the cells and construct the parameters for the Border constructor that are appropriate for each cell in the sheet.

for i in range(1, len(df) + 2):  # Excel indexes at 1 and header row is extra
    for j in range(1, len(headers) + 1):
        sides = {"top": Side(), "bottom": Side(), "left": Side(), "right": Side()}
        if j == 1:  # Left Most Column:
            sides["left"] = thin_border

        if i == 1:  # Top Row
            sides["top"] = thin_border

        if j == len(headers):  # Right Most Column
            sides["right"] = thin_border

        if i == len(df) + 1:  # Bottom Row
            sides["bottom"] = thin_border

        ws.cell(i, j).border = Border(**sides)  # Apply sides to current cell

wb.save("output.xlsx")

Note that I had to use Border(**sides) since the Side objects are immutable in the package. I'm not sure if there's a more efficient way to do this, since I don't have a lot of experience with the package, but this gets it done.

It should be straightforward from here to apply bordering however you see fit.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM