A-A+

Python openpyxl 处理 excel xlsm

2021年04月15日 20:32 汪洋大海 暂无评论 阅读 70 views 次

处理表格
 

from openpyxl import load_workbook
import datetime 
wb = load_workbook(r'D:\Pythontest\reptile\python-excel.xlsx')

 
 
#创建一个sheet

ws1=wb.create_sheet("mysheet")

 
 
#设定sheet的名字

ws1.title='newtitle'

 
 
读取.xlsx文件

# coding=utf-8

from openpyxl import load_workbook
 
#打开一个workbook
#wb = load_workbook('D:\\python\\TEST.xlsx')
wb = load_workbook("TEST.xlsx")
 
#获取当前活跃的worksheet,默认就是第一个worksheet
#ws = wb.active
 
#当然也可以使用下面的方法
 
#获取所有表格(worksheet)的名字
sheets = wb.sheetnames
#第一个表格的名称
sheet_first = sheets[0]
#获取特定的worksheet
ws = wb[sheet_first]
 
#获取表格所有行和列,两者都是可迭代的
rows = ws.rows
columns = ws.columns
 
#迭代所有的行
for row in rows:
    line = [col.value for col in row]
    print(line)
 
#通过坐标读取值
   # A表示列,1表示行print ws.cell(row=1, column=1).value
print(ws['A1'].value)

 
 
#设定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
# print(wb.sheetnames)  # 获取excel当前工作薄里所有的工作表 以list形式显示
# print(wb.active)  # 获取excel正在使用的表,即打开excel会显示的表;

 
 
#调整列宽

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

 
 
写.xlsx操作

# coding=utf-8

from openpyxl import Workbook
from openpyxl.utils import get_column_letter
 
# 在内存中创建一个workbook对象,而且会至少创建一个 worksheet
wb = Workbook()
 
#获取当前活跃的worksheet,默认就是第一个worksheet
ws = wb.active
 
#设置单元格的值,A1等于6(测试可知openpyxl的行和列编号从1开始计算),B1等于7
ws.cell(row=1, column=1).value = 6
ws['B1'].value = 7
 
#从第2行开始,写入9行10列数据,值为对应的列序号A、B、C、D...
for row in range(2,11):
    for col in range (1,11):
        ws.cell(row=row, column=col).value = get_column_letter(col)
 
#可以使用append插入一行数据
ws.append(["我","你","她"])
 
#保存
wb.save("TEST.xlsx")
print('保存完毕')

 
 
#完整格式设置

#字体
    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 xlsm

颜色编码参照表

以上文章来源:https://blog.csdn.net/qq_42819930/article/details/89463202

Python用openpyxl库读写Excel、xlsx文件

#!/usr/bin/python
# -*- coding: utf-8 -*-

import openpyxl
import re

# 通过 openpyxl 加载
wb = openpyxl.load_workbook('E:\杂乱\with body.xlsx')

# print(wb.sheetnames)  # 获取excel当前工作薄里所有的工作表 以list形式显示
# print(wb.active)  # 获取excel正在使用的表,即打开excel会显示的表;

# 选择要操作的工作表, 返回工作表对象
sheet = wb.worksheets[0]  # 等同于 wb[wb.sheetnames[0]]  读取指定工作表

# 获取表格所有行和列,两者都是可迭代的
rows = sheet.rows  # 所有行的内容
columns = sheet.columns  # 所有列的内容

# 迭代所有的行
i = 0
for row in rows:
    i = i + 1
    line = [col.value for col in row]
    if i == 1:
        sheet.cell(row=i, column=5).value = "手机号匹配"
    # 方法一:限制手机号开头,或者手机号前面为非数字,且手机号结尾或者以非数字结尾
    pattern1 = "(?:^|[^\d])(1[3-9]\d{9})(?:$|[^\d])"
    phone_list1 = re.compile(pattern1).findall(line[1])
    if phone_list1:
        sheet.cell(row=i, column=5).value = "{}".format(',\n'.join(phone_list1))

wb.save('E:\杂乱\with body.xlsx')

布施恩德可便相知重

微信扫一扫打赏

支付宝扫一扫打赏

×

给我留言