簡體   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