是否可以使用 openpyxl 在 table 中创建竖线?

Is it possible to create a vertical bar in a table with openpyxl?

我正在使用 Python 创建带有 openpyxl 包的 xlsx 文件。我创建了简单的 table 并且我想用竖线分隔列。 问题:如何通过openpyxl创建竖线?

Question: How to create a vertical bar via openpyxl?

您可以使用样式 borderfill

OpenPyXL Working with styles
Styles are used to change the look of your data while displayed on screen. They are also used to determine the formatting for numbers.

例如:

from openpyxl import Workbook
wb = Workbook()
ws = wb.worksheets[0]

data = [['A1', '', 'C1', '', 'E1'], ['A2', '', 'C2', '', 'E2'], ['A3', '', 'C3', '', 'E3'], ['A4', '', 'C4', '', 'E4']]
for row, rData in enumerate(data, 1):
    ws.append(rData)

from openpyxl.styles import Side, Border, PatternFill, Color
thin = Side(border_style="thin", color="000000")
thin_white = Side(border_style="thin", color="FFFFFF")
border = Border(left=thin)
fill = PatternFill("solid", fgColor="666666")

from openpyxl.utils import range_boundaries
ws.column_dimensions['B'].width = 1
ws.column_dimensions['D'].width = 0.5
min_col, min_row, max_col, max_row = range_boundaries('B1:D4')
B = 0; D = 2
for row_cells in ws.iter_rows(min_col=min_col, min_row=min_row,
                                   max_col=max_col, max_row=max_row):

    row_cells[B].border = border
    row_cells[D].fill = fill
    row_cells[D].border = Border(left=thin_white, right=thin_white)

wb.save('../test/test.xlsx')

Output:

测试 Python: 3.4.2 - openpyxl: 2.4.1 - LibreOffice: 4.3.3.2