我需要一种简单的方法来设置多个单元格的边框,如下所示:
我发现的只是 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/