600字范文,内容丰富有趣,生活中的好帮手!
600字范文 > 用Python中openpyxl处理excel设置单元格格式

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

时间:2021-11-21 08:19:48

相关推荐

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

处理表格

from openpyxl import load_workbookimport 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.5d=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_rangefor row in row_range:for cell in row:print cell.valuefor 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.rowsfor row in ws1.rows:print row#获取所有列print ws1.columnsfor 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(,7,21)print(ws['B2'].number_format)#yyyy-mm-dd h:mm:ssws['B3']='12%'print(ws['B3'].number_format)#General

#使用公式

ws["A1"]=1ws["A2"]=2ws["A3"]=3ws["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.activeimport openpyxlfrom openpyxl.styles import fills,colors,NamedStyle,Font,Side,Border,PatternFill,Alignment,Protectionfor 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=fontif 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~180wrap_text=False,#文字换行shrink_to_fit=True,#自适应宽度,改变文字大小,上一项falseindent=0)number_format = 'General'protection = Protection(locked=True,hidden=False)ws["B5"].font = ftws["B5"].fill =fillws["B5"].border = bdws["B5"].alignment = alignmentws["B5"].number_format = number_formatws["B5"].value ="123"wb.save(r'D:\Pythontest\reptile\豆瓣排名250.xlsx')

#颜色编码参照表

/yingyong/yanse-rgb-16/

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。