用Python中openpyxl处理excel设置单元格格式

处理表格

from openpyxl import load_workbook
import datetime 
wb = load_workbook(r'D:\Pythontest\reptile\豆瓣排名250.xlsx')

#创建一个sheet

ws1=wb.create_sheet("mysheet")

#设定sheet的名字

ws1.title='newtitle'

#设定sheet的标签的背景颜色

ws1.sheet_properties.tabColor='1072BA'

#获取某个sheet对象

print(wb.get_sheet_by_name("newtitle"))
print(wb["newtitle"])

#遍历sheet名字

print(wb.sheetnames)
for sheetname in wb.sheetnames:
    print(sheetname)
for sheet in wb:
    print(sheet.title)

#复制一个sheet

wb['newtitle']['A1']='123'
source=wb["newtitle"]
target=wb.copy_worksheet(source)

#操作单元格

ws = wb.active

#调整列宽

ws.column_dimensions['A'].width = 10

#调整行高

ws.row_dimensions[1].height = 13.5
d=ws.cell(row=4,column=2)
#d=ws.cell(row=4,column=2,value=10)//更改该单元格的值
print(d.value)

#操作单列

print(ws['B'])
for cell in ws['B']:
    print(cell.value)

#操作多列

print(ws["A:C"])
for column in ws["A:C"]:
    for cell in column:
        print(cell.value)

#操作多行

row_range = ws1[1:3]
print row_range
for row in row_range:
    for cell in row:
        print cell.value
for row in ws1.iter_rows(min_row=1, min_col=1, max_col=3, max_row=3):
    for cell in row:
        print cell.value

#获取所有行

print ws1.rows
for row in ws1.rows:
    print row
#获取所有列
print ws1.columns
for col in ws1.columns:
    print col

#获取所有的行对象

rows1=[]
for row in ws.iter_rows():
    rows1.append(row)
print(rows1[2][3].value)

#获取所有的列对象

col1=[]
for col in ws.iter_cols():
    col1.append(col)
print(col1[2][2].value)

#单元格格式

ws['B2']=datetime.datetime(2010,7,21)
print(ws['B2'].number_format)#yyyy-mm-dd h:mm:ss
ws['B3']='12%'
print(ws['B3'].number_format)#General

#使用公式

ws["A1"]=1
ws["A2"]=2
ws["A3"]=3
ws["A4"] = "=SUM(1, 1)"
ws["A5"] = "=SUM(A1:A3)"
print (ws["A4"].value ) #打印的是公式内容,不是公式计算后的值,程序无法取到计算后的值
print (ws["A5"].value) #=SUM(A1:A3)

#合并单元格

ws.merge_cells('B2:B4')
ws.merge_cells(start_row=2,start_column=1,end_row=2,end_column=4)

#拆分单元格

ws.unmerge_cells('B2:B4')
ws.unmerge_cells(start_row=2,start_column=1,end_row=2,end_column=4)

#隐藏单元格

ws.column_dimensions.group('A','D',hidden=False)
ws.row_dimensions.group(5,7,hidden=False)

#设定字体格式Font()

ws=wb.active
import openpyxl
from openpyxl.styles import fills,colors,NamedStyle,Font,Side,Border,PatternFill,Alignment,Protection
for irow,row in enumerate(ws.rows,start=1): #           加粗        斜体        下划线
        font=Font('微软雅黑',size=11,color=colors.BLACK,bold=False,italic=True,underline='double')
    for cell in row:
        cell.font=font
        if irow%3==0:
            cell.fill=fills.GradientFill(stop=['FF0000', '0000FF'])#填充渐变

from openpyxl.styles import fills,colors,NamedStyle,Font,Side,Border,PatternFill,Alignment,Protection

#完整格式设置

#字体
    ft = Font(name=u'微软雅黑',
        size=11,
        bold=True,
        italic=True,#斜体
        vertAlign='baseline',#上下标'subscript','baseline'='none,'superscript'
        underline='single',#下划线'singleAccounting', 'double', 'single', 'doubleAccounting'
        strike=False ,#删除线
        color='00FF00')
    
    fill = PatternFill(fill_type="solid",
        start_color='FFFFFF',#单元格填充色
        end_color='FFFFFF')
    
#边框   可以选择的值为:'hair', 'medium', 'dashDot', 'dotted', 'mediumDashDot', 'dashed', 'mediumDashed', 'mediumDashDotDot', 'dashDotDot', 'slantDashDot', 'double', 'thick', 'thin']
    bd = Border(left=Side(border_style="thin",
                  color='0000FF'),
        right=Side(border_style="double",
                   color='5C3317'),
        top=Side(border_style="thin",
                 color='FF110000'),
        bottom=Side(border_style="hair",
                    color='238E23'),
        diagonal=Side(border_style='dashed',#对角线
                      color='3299CC'),
        diagonal_direction=1,
        outline=Side(border_style='slantDashDot',#外边框
                     color='BC1717'),
        vertical=Side(border_style='medium',#竖直线
                      color=colors.BLACK),
        horizontal=Side(border_style='dotted',#水平线
                       color=colors.WHITE)
                    )
 #对齐方式
    alignment=Alignment(horizontal='center',#水平'center', 'centerContinuous', 'justify', 'fill', 'general', 'distributed', 'left', 'right'
            vertical='top',#垂直'distributed', 'bottom', 'top', 'center', 'justify'
            text_rotation=0,#旋转角度0~180
            wrap_text=False,#文字换行
            shrink_to_fit=True,#自适应宽度,改变文字大小,上一项false
            indent=0)
    
    number_format = 'General'
    
    protection = Protection(locked=True,
                hidden=False)
    
    ws["B5"].font = ft
    ws["B5"].fill =fill
    ws["B5"].border = bd
    ws["B5"].alignment = alignment
    ws["B5"].number_format = number_format
    
    ws["B5"].value ="123"
    wb.save(r'D:\Pythontest\reptile\豆瓣排名250.xlsx')

#颜色编码参照表
《用Python中openpyxl处理excel设置单元格格式》
https://www.sioe.cn/yingyong/yanse-rgb-16/

    原文作者:Mr_zhaohl
    原文地址: https://blog.csdn.net/qq_42819930/article/details/89463202
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞