繁体   English   中英

使用 Python xlwings 设置边框

[英]Set border using Python xlwings

有没有办法使用 xlwings 从 Python 为 Excel 文件设置边界线? 我正在查看文档,但无法弄清楚。

我想使用 xlwings 创建这样的文件在此处输入图像描述

据我所知,目前这不是 xlwings 内置的功能。 但是,您可以使用此处xlwings 文档中描述的较低级别的 pywin32 函数(带有警告)。

下面是一个简短的示例,说明如何使用此方法在单个单元格上设置边框:

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

通过 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

例如

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

通过BorderWeight也有一些权重预设。

我有时会编写代码来帮助我记住如何做事。 这是一个小定义 function 以及使用 xlwings 设置边框的使用示例。 对文档的链接进行了注释。

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