openpyxl加框线
时间: 2023-10-31 18:07:44 浏览: 79
openpyxl是一个用于读写Excel文件的Python库,它可以用来给Excel单元格添加边框。具体来说,可以通过设置单元格的border属性来实现。可以设置边框的样式、颜色和粗细等属性。同时,也可以给某个区域设置边框样式,包括表格内部和外部的边框。下面是两种常见的加框线的方法:
1. 给指定单元格添加边框
可以通过定义一个函数来设置单元格的边框样式,然后调用该函数来给指定的单元格添加边框。具体代码如下:
```
from openpyxl import Workbook, load_workbook
from openpyxl.styles import *
# 打开Excel文件
wb = load_workbook('example.xlsx')
# 选择要操作的Sheet
ws = wb['Sheet1']
# 定义函数,设置单元格边框样式
def format_border_cell(ws, row_index, col_index):
ws.cell(row=row_index, column=col_index).border = Border(
top=Side(border_style='thick', color='FF000000'),
right=Side(border_style='thick', color='FF000000'),
bottom=Side(border_style='thick', color='FF000000'),
left=Side(border_style='thick', color='FF000000')
)
# 调用函数,给指定单元格添加边框
format_border_cell(ws, 1, 1)
# 保存Excel文件
wb.save('example.xlsx')
```
2. 给某个区域设置边框样式
可以通过遍历某个区域内的所有单元格,分别设置它们的边框样式来实现。具体代码如下:
```
from openpyxl import Workbook, load_workbook
from openpyxl.styles import *
# 打开Excel文件
wb = load_workbook('example.xlsx')
# 选择要操作的Sheet
ws = wb['Sheet1']
# 定义函数,设置单元格边框样式
def format_border_range(ws, start_row, start_col, end_row, end_col):
# 设置表格内部的边框样式
for row in range(start_row, end_row+1):
for col in range(start_col, end_col+1):
ws.cell(row=row, column=col).border = Border(
top=Side(border_style='thin', color='FF000000'),
right=Side(border_style='thin', color='FF000000'),
bottom=Side(border_style='thin', color='FF000000'),
left=Side(border_style='thin', color='FF000000')
)
# 设置表格外部的边框样式
ws.cell(row=start_row, column=start_col).border = Border(
top=Side(border_style='medium', color='FF000000'),
right=Side(border_style='medium', color='FF000000'),
bottom=Side(border_style='thin', color='FF000000'),
left=Side(border_style='medium', color='FF000000')
)
ws.cell(row=start_row, column=end_col).border = Border(
top=Side(border_style='medium', color='FF000000'),
right=Side(border_style='medium', color='FF000000'),
bottom=Side(border_style='thin', color='FF000000'),
left=Side(border_style='thin', color='FF000000')
)
ws.cell(row=end_row, column=start_col).border = Border(
top=Side(border_style='thin', color='FF000000'),
right=Side(border_style='medium', color='FF000000'),
bottom=Side(border_style='medium', color='FF000000'),
left=Side(border_style='medium', color='FF000000')
)
ws.cell(row=end_row, column=end_col).border = Border(
top=Side(border_style='thin', color='FF000000'),
right=Side(border_style='medium', color='FF000000'),
bottom=Side(border_style='medium', color='FF000000'),
left=Side(border_style='thin', color='FF000000')
)
# 调用函数,给指定区域添加边框
format_border_range(ws, 1, 1, 5, 5)
# 保存Excel文件
wb.save('example.xlsx')
```
阅读全文