使用xlsxwritter添加外边界

时间:2019-03-20 14:47:49

标签: python-3.x xlsxwriter

我有一个数据框,我想设置外框。我尝试了下面的代码,但它为'A1:I83'范围内的每个单元格添加了边框。我只想添加外部粗边框:

border_format=workbook.add_format({
                            'border':1,
                            'align':'left',
                            'font_size':10
                           })
worksheet_rating_input.conditional_format('A1:I83' , { 'type' : 'no_blanks' , 'format' : border_format})

1 个答案:

答案 0 :(得分:1)

一种方法是,将J1到J183的格式设置为带有粗边框,并将A184的格式设置为I184,以使其具有粗顶边框。

我在下面发布了一个完全可复制的示例。在我的示例中,我使用df.shape来设置边框,具体取决于数据框的尺寸。

import xlsxwriter
import pandas as pd
import numpy as np

# Creating a dataframe 
df = pd.DataFrame(np.random.randn(182, 9), columns=list('ABCDEFGHI'))
column_list = df.columns
# Create a Pandas Excel writer using XlsxWriter engine.
writer = pd.ExcelWriter("test.xlsx", engine='xlsxwriter')

df.to_excel(writer, index=False)

workbook  = writer.book
worksheet = writer.sheets['Sheet1']

leftFormat = workbook.add_format({'left': 5})
topFormat = workbook.add_format({'top': 5})

for row in range(0, df.shape[0] + 1):
    worksheet.write(row, df.shape[1], '', leftFormat)

for col in range(0, df.shape[1]):
    worksheet.write(df.shape[0] + 1, col, '', topFormat)

worksheet.freeze_panes(1, 0) #freezing top row 

writer.save() 

具有预期的输出:

Expected Output