用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')

#颜色编码参照表
在这里插入图片描述
https://www.sioe.cn/yingyong/yanse-rgb-16/

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值