python XlsxWriter围绕多个单元格设置边框 [英] python XlsxWriter set border around multiple cells

查看:3606
本文介绍了python XlsxWriter围绕多个单元格设置边框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个简单的方法来设置多个单元格的边框,如:

I need an easy way to set border around multiple cells, like so:

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

All I found was border of 1 cell, and merge cells, which is not what I need.

我期待着像:

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

有没有办法可以完成(这不涉及设置top_border,bottom_border,
left_border,right_border for每个单元格)?

Is there a way that this can be done (that is not involving setting top_border, bottom_border, left_border, right_border for each cell individually)?

推荐答案

XlsxWriter是一个令人敬畏的模块,使我的旧工作更容易1000x(谢谢约翰!),但格式化单元格可以要耗费时间。我有几个帮助函数,我用来做这样的事情。

XlsxWriter is an awesome module that made my old job 1,000x easier (thanks John!), but formatting cells with it can be time-consuming. I've got a couple helper functions I use to do stuff like this.

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

First, you need to be able to create a new format by adding properties to an existing format:

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())))

现在构建该功能with:

Now build off of that function with:

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围绕多个单元格设置边框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆