简体   繁体   English

使用 Python xlwings 设置边框

[英]Set border using Python xlwings

Is there a way to set border lines for an Excel file from Python using xlwings?有没有办法使用 xlwings 从 Python 为 Excel 文件设置边界线? I was looking at the documentation but cannot figure out.我正在查看文档,但无法弄清楚。

I want to create a file like this using xlwings我想使用 xlwings 创建这样的文件在此处输入图像描述

As far as I know, this isn't a feature that's built into xlwings at this point.据我所知,目前这不是 xlwings 内置的功能。 However, you can use the lower level pywin32 functions (with caveats) as described in the xlwings docs here .但是,您可以使用此处xlwings 文档中描述的较低级别的 pywin32 函数(带有警告)。

Here's a brief example of how to set borders on a single cell using this method:下面是一个简短的示例,说明如何使用此方法在单个单元格上设置边框:

rng = xw.Range('A1').xl_range
for border_id in xrange(7,13):
    rng.Borders(border_id).LineStyle=1
    rng.Borders(border_id).Weight=2

尽管这可能很烦人,但您还可以编写(或记录)一个创建边框的宏,然后在需要时使用 xlwings 从 Python 调用该宏。

sht.range('A1:C5').api.Borders.Weight = 1

There are descriptive accessors to the border indices available in the constants module via class BordersIndex seen here .通过 class BordersIndexconstants模块中可以看到边界索引的描述性访问器,请参见此处

class BordersIndex:
    xlDiagonalDown = 5  # from enum XlBordersIndex
    xlDiagonalUp = 6  # from enum XlBordersIndex
    xlEdgeBottom = 9  # from enum XlBordersIndex
    xlEdgeLeft = 7  # from enum XlBordersIndex
    xlEdgeRight = 10  # from enum XlBordersIndex
    xlEdgeTop = 8  # from enum XlBordersIndex
    xlInsideHorizontal = 12  # from enum XlBordersIndex
    xlInsideVertical = 11  # from enum XlBordersIndex

Eg例如

import xlwings as xw
rng = xw.range('A1')
rng.Borders(xw.constants.BordersIndex.xlEdgeTop).Weight = 2

There are also some weight presets via BorderWeight .通过BorderWeight也有一些权重预设。

I sometimes write code to help me remember how to do things.我有时会编写代码来帮助我记住如何做事。 This is a little def function with usage examples for setting up borders using xlwings.这是一个小定义 function 以及使用 xlwings 设置边框的使用示例。 Links to documentation are commented in.对文档的链接进行了注释。

import pandas as pd
import xlwings as xw

def format_borders(xl_range_obj, weight, XlBordersIndex = 'All', color = 0):

# documentation for borders object:
#   https://docs.microsoft.com/en-us/office/vba/api/excel.borders
# documentation for border object:
#   https://docs.microsoft.com/en-us/office/vba/api/excel.border(object)
# enumeration for xlbordersindex object:
#   https://docs.microsoft.com/en-us/office/vba/api/excel.xlbordersindex
# enumeration for xlborderweight object
#https://docs.microsoft.com/en-us/office/vba/api/excel.xlborderweight

    try:
        border_dict = {'xlEdgeLeftAll'      : 1,    # Left edge of each cell in range, not in enumeration docs
                       'xlEdgeRightAll'     : 2,    # Right edge of each cell in range, not in enumeration docs
                       'xlEdgeTopAll'       : 3,    # Top edge of each cell in range, not in enumeration docs
                       'xlEdgeBottomAll'    : 4,    # Bottom edge of each cell in range, not in enumeration docs
                       'xlDiagonalDown'     : 5,    # Border running from the upper-left corner to the lower-right of each cell in the range.
                       'xlDiagonalUp'       : 6,    # Border running from the lower-left corner to the upper-right of each cell in the range.
                       'xlEdgeLeft'         : 7,    # Border at the left edge of the range.
                       'xlEdgeTop'          : 8,    # Border at the top of the range.
                       'xlEdgeBottom'       : 9,    # Border at the bottom of the range.
                       'xlEdgeRight'        : 10,   # Border at the right edge of the range.
                       'xlInsideVertical'   : 11,   # Vertical borders for all the cells in the range except borders on the outside of the range.
                       'xlInsideHorizontal' : 12}   # Horizontal borders for all cells in the range except borders on the outside of the range.
    
        # Custom function to "cross out" all cells in the range
        if XlBordersIndex == 'xlCrossoutAll':
            xl_range_obj.api.Borders(5).Weight = weight
            xl_range_obj.api.Borders(5).Color = color
            xl_range_obj.api.Borders(6).Weight = weight
            xl_range_obj.api.Borders(6).Color = color
            return ''

        # Custom function to format the bottom and right edges for all cells in the range
        elif XlBordersIndex == 'xlBottomRightAll': 
            xl_range_obj.api.Borders(2).Weight = weight
            xl_range_obj.api.Borders(2).Color = color
            xl_range_obj.api.Borders(4).Weight = weight
            xl_range_obj.api.Borders(4).Color = color
            return ''

        else:
            edge = border_dict.get(XlBordersIndex, 0)
            if edge:
                xl_range_obj.api.Borders(edge).Weight = weight
                xl_range_obj.api.Borders(edge).Color = color
                return ''
            else:
                xl_range_obj.api.Borders.Weight = weight
                xl_range_obj.api.Borders.Color = color
                if XlBordersIndex != 'All':
                    return f'XlBordersIndex = "{XlBordersIndex}" not found.  Formatted all edges.'
                else:
                    return ''

    except Exception as e:
        return f'Exception = {e}'

# set up dataframe for example
pd_list = ['b', 'c', 'd', 'e', 'f']
pd_columns =  [f'Col_{__e}' for __e in pd_list]
pd_list = [[f'{__e}{__i+4}' for __e in pd_list] for __i in range(len(pd_list))]
df = pd.DataFrame(pd_list, columns = pd_columns
title = ['This is the table title']

#load Workbook
wb = xw.Book()
sht = wb.sheets[0]

# Set up the dataframe in Excel
sht.range('B1:H1').api.merge()
sht["A1"].value ='Title:'
sht["B1"].value = title
sht["A3"].options(pd.DataFrame, header=1, index=True, expand='table').value = df
sht["A1"].expand("right").api.Font.Bold = True
sht["A3"].expand("right").api.Font.Bold = True
sht["A3"].expand("down").api.Font.Bold = True
 
# format borders with direct call
sht["A1"].expand("right").api.Borders(9).Color = xw.utils.rgb_to_int((255,0,0))
sht["A1"].expand("right").api.Borders(9).Weight = 4

# set color "red"
red = xw.utils.rgb_to_int((255,0,0))

# format borders in different ways with def function calls
format_borders(sht["A3"].expand("right"), 2, XlBordersIndex = 'xlBottomRightAll'
format_borders(sht["A3"].expand("down"), 2, XlBordersIndex = 'xlBottomRightAll')
format_borders(sht['A1:H1'], 4, XlBordersIndex = 'xlEdgeBottom', color = red)
format_borders(sht['C6:D7'], 4, 'xlCrossoutAll', red)
format_borders(sht["F8"], 3)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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