python XlsxWriter在多个单元格周围设置边框

标签 python excel xlsxwriter

我需要一种简单的方法来设置多个单元格的边框,如下所示: Border around cells

我发现的只是 1 个单元格的边框和合并单元格,这不是我需要的。

我期待的是这样的:

worksheet.range_border(first_row, first_col, last_row, last_col)

有没有办法做到这一点(不涉及设置top_border,bottom_border, left_border, right_border 分别为每个单元格)?

最佳答案

XlsxWriter 是一个很棒的模块,它让我以前的工作轻松了 1,000 倍(感谢 John!),但使用它格式化单元格可能很耗时。我有几个辅助函数可以用来做这样的事情。

首先,您需要能够通过向现有格式添加属性来创建新格式:

def add_to_format(existing_format, dict_of_properties, workbook):
    """Give a format you want to extend and a dict of the properties you want to
    extend it with, and you get them returned in a single format"""
    new_dict={}
    for key, value in existing_format.__dict__.iteritems():
        if (value != 0) and (value != {}) and (value != None):
            new_dict[key]=value
    del new_dict['escapes']

    return(workbook.add_format(dict(new_dict.items() + dict_of_properties.items())))

现在使用以下功能构建该功能:

def box(workbook, sheet_name, row_start, col_start, row_stop, col_stop):
    """Makes an RxC box. Use integers, not the 'A1' format"""

    rows = row_stop - row_start + 1
    cols = col_stop - col_start + 1

    for x in xrange((rows) * (cols)): # Total number of cells in the rectangle

        box_form = workbook.add_format()   # The format resets each loop
        row = row_start + (x // cols)
        column = col_start + (x % cols)

        if x < (cols):                     # If it's on the top row
            box_form = add_to_format(box_form, {'top':1}, workbook)
        if x >= ((rows * cols) - cols):    # If it's on the bottom row
            box_form = add_to_format(box_form, {'bottom':1}, workbook)
        if x % cols == 0:                  # If it's on the left column
            box_form = add_to_format(box_form, {'left':1}, workbook)
        if x % cols == (cols - 1):         # If it's on the right column
            box_form = add_to_format(box_form, {'right':1}, workbook)

        sheet_name.write(row, column, "", box_form)

关于python XlsxWriter在多个单元格周围设置边框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21599809/

相关文章:

python - 合法 .xlsx 文件上的 openpyxl load_workbook() 会导致 zipfile.BadZipFile 错误

python - 如何以不同的用户(本地用户)身份运行通过 root 运行的 python 脚本,然后返回到 root

excel - 如何使用 Worksheet_Change 函数找到的表中的值自动填充电子邮件正文

Python/Excel - IOError : [Errno 2] No such file or directory:

python - 如何将具有多个行标题的 Excel 数据插入到 pandas 数据框中

sql - 在 Excel 表上编写 SQL 查询

Java - 打开 CSV - .csv 到 .xls 扩展名

python - 除了使用 xlsxwriter 进行列格式化外,逐行应用格式化

python - 试图将文件名传递给 ExcelWriter

python - 修补一个方法而不改变该方法的工作方式?