您的当前位置:首页正文

openpyxl合并单元格

来源:东饰资讯网

拳不离手,曲不离口。没事找事,用全国计算机等级考试一级MS OFFICE的EXCEL操作题练练手。

打开EXCEL.xlsx,将Sheet1工作表中的A1:G1单元格合并为一个单元格,内容水平居中,并同名保存结果。

代码:

from openpyxl.styles import Alignment
from openpyxl import load_workbook

wb = load_workbook("excel.xlsx")

ws = wb["Sheet1"]

ws.merge_cells('A1:G1')

ws['A1'].alignment = Alignment(horizontal = "center", vertical = "center")

wb.save("excel.xlsx")

参考资料:

1、Merge  合并单元格

from openpyxl.workbook import Workbook

wb = Workbook()
ws = wb.active

ws.merge_cells('A2:D2')

# or equivalently
ws.merge_cells(start_row = 3, start_column =1, end_row = 3, end_column = 4)

wb.save("merge.xlsx")

2、Unmerge cells 取消单元格合并

from openpyxl.workbook import Workbook
from openpyxl import load_workbook

wb = load_workbook("merge.xlsx")
ws = wb.active

ws.unmerge_cells('A2:D2')

# or equivalently
ws.unmerge_cells(start_row = 3, start_column =1, end_row = 3, end_column = 4)

wb.save("merge.xlsx")

3、Styling merged cells  合并单元格样式()

from openpyxl.styles import Border, Side, PatternFill, Font, GradientFill, Alignment
from openpyxl import Workbook

wb = Workbook()
ws = wb.active
ws.merge_cells('B2:F4')

top_left_cell = ws['B2']
top_left_cell.value = "My Cell"

thin = Side(border_style = "thin", color = "000000")
double = Side(border_style = "double", color = "ff0000")

top_left_cell.border = Border(top = double, left = thin, right = thin, bottom = double)
top_left_cell.fill = PatternFill("solid", fgColor = "DDDDDD")
top_left_cell.fill = Fill = GradientFill(stop = ("000000", "FFFFFF"))
top_left_cell.font = Font(b = True, color = "FF0000")
top_left_cell.alignment = Alignment(horizontal = "center", vertical = "center")

wb.save("styled.xlsx")

4、Alignment属性设置单元格对齐方式。

水平对齐方式

垂直对齐方式

horizontal = ‘left’

左对齐

vertical = ‘top’

 顶部对齐

horizontal = ‘center’

居中对齐

vertical = ‘center’

居中对齐

horizontal = ‘right’

右对齐

vertical = ‘bottom’

底部对齐

horizontal = ‘justify’

两端对齐

vertical = ‘justify’

两端对齐

horizontal = ‘distributed’

分散对齐

vertical = ‘distributed’

分散对齐

因篇幅问题不能全部显示,请点此查看更多更全内容