详解

安装

pip install openpyxl

打开文件

  • 创建

      from  openpyxl import  Workbook 
      # 实例化
      wb = Workbook()
      # 激活 worksheet
      ws = wb.active
    
  • 打开已有

      from openpyxl  import load_workbook
      wb2 = load_workbook('文件名称.xlsx')
    
  • 储存数据

    # 方式一:数据可以直接分配到单元格中(可以输入公式)
    ws['A1'] = 42
    # 方式二:可以附加行,从第一列开始附加(从最下方空白处,最左开始)(可以输入多行)
    ws.append([1, 2, 3])
    # 方式三:Python 类型会被自动转换
    ws['A3'] = datetime.datetime.now().strftime("%Y-%m-%d")
    

    创建表(sheet)

    # 方式一:插入到最后(default)
    >>> ws1 = wb.create_sheet("Mysheet") 
    # 方式二:插入到最开始的位置
    >>> ws2 = wb.create_sheet("Mysheet", 0)
    

    选择表(sheet)

    # sheet 名称可以作为 key 进行索引
    >>> ws3 = wb["New Title"]
    >>> ws4 = wb.get_sheet_by_name("New Title")
    >>> ws is ws3 is ws4
    True
    

    查看表名(sheet)

    # 显示所有表名
    >>> print(wb.sheetnames)
    ['Sheet2', 'New Title',  'Sheet1']
    # 遍历所有表
    >>> for sheet in  wb:
    ... 	print(sheet.title)
    

    访问单元格(call)

  • 单一单元格访问

      # 方法一
      >>> c = ws['A4']
      # 方法二:row 行;column 列
      >>> d = ws.cell(row=4, column=2, value=10)
      # 方法三:只要访问就创建
      >>> for i in  range(1,101):
      ...         for j in range(1,101):
      ...            ws.cell(row=i, column=j)
    
  • 多单元格访问

    # 通过切片
    >>> cell_range = ws['A1':'C2']
    # 通过行(列)
    >>> colC = ws['C']
    >>> col_range = ws['C:D']
    >>> row10 = ws[10]
    >>> row_range = ws[5:10]
    # 通过指定范围(行 → 行)
    >>> for row in  ws.iter_rows(min_row=1, max_col=3, max_row=2):
    ...    for cell in  row:
    ...        print(cell)
    <Cell Sheet1.A1>
    <Cell Sheet1.B1>
    <Cell Sheet1.C1>
    <Cell Sheet1.A2>
    <Cell Sheet1.B2>
    <Cell Sheet1.C2> 
    # 通过指定范围(列 → 列)
    >>> for row in  ws.iter_rows(min_row=1, max_col=3, max_row=2):
    ...    for cell in  row:
    ...        print(cell)
    <Cell Sheet1.A1>
    <Cell Sheet1.B1>
    <Cell Sheet1.C1>
    <Cell Sheet1.A2>
    <Cell Sheet1.B2>
    <Cell Sheet1.C2>
    # 遍历所有 方法一
    >>> ws = wb.active
    >>> ws['C9'] = 'hello world'
    >>> tuple(ws.rows)
    ((<Cell Sheet.A1>, <Cell Sheet.B1>, <Cell Sheet.C1>),
    (<Cell Sheet.A2>, <Cell Sheet.B2>, <Cell Sheet.C2>),
    ...
    (<Cell Sheet.A8>, <Cell Sheet.B8>, <Cell Sheet.C8>),
    (<Cell Sheet.A9>, <Cell Sheet.B9>, <Cell Sheet.C9>))
    # 遍历所有 方法二
    >>> tuple(ws.columns)
    ((<Cell Sheet.A1>,
    <Cell Sheet.A2>,
    <Cell Sheet.A3>,
    ...
    <Cell Sheet.B7>,
    <Cell Sheet.B8>,
    <Cell Sheet.B9>),
    (<Cell Sheet.C1>,
    ...
    <Cell Sheet.C8>,
    <Cell Sheet.C9>))
    
  • 保存数据

    >>> wb.save('文件名称.xlsx')
    

    改变 sheet 标签按钮颜色

    ws.sheet_properties.tabColor = "1072BA"
    

    获取最大行,最大列

    # 获得最大列和最大行
    print(sheet.max_row)
    print(sheet.max_column)
    

    获取每一行,每一列

  • sheet.rows为生成器, 里面是每一行的数据,每一行又由一个tuple包裹。

  • sheet.columns类似,不过里面是每个tuple是每一列的单元格。

      # 因为按行,所以返回A1, B1, C1这样的顺序
      for row in sheet.rows:
          for cell in row:
              print(cell.value)
      
      # A1, A2, A3这样的顺序
      for column in sheet.columns:
          for cell in column:
              print(cell.value)
    
  • 根据数字得到字母,根据字母得到数字

    from openpyxl.utils import get_column_letter, column_index_from_string
    
    # 根据列的数字返回字母
    print(get_column_letter(2))  # B
    # 根据字母返回列的数字
    print(column_index_from_string('D'))  # 4
    

    删除工作表

    # 方式一
    wb.remove(sheet)
    # 方式二
    del wb[sheet]
    

    矩阵置换(行 → 列)

    rows = [
        ['Number', 'data1', 'data2'],
        [2, 40, 30],
        [3, 40, 25],
        [4, 50, 30],
        [5, 30, 10],
        [6, 25, 5],
        [7, 50, 10]]
    
    list(zip(*rows))
    
    # out
    [('Number', 2, 3, 4, 5, 6, 7),
     ('data1', 40, 40, 50, 30, 25, 50),
     ('data2', 30, 25, 30, 10, 5, 10)]
    
    # 注意 方法会舍弃缺少数据的列(行)
    rows = [
        ['Number', 'data1', 'data2'],
        [2, 40	  ],	# 这里少一个数据
        [3, 40, 25],
        [4, 50, 30],
        [5, 30, 10],
        [6, 25, 5],
        [7, 50, 10],
    ]
    # out
    [('Number', 2, 3, 4, 5, 6, 7), ('data1', 40, 40, 50, 30, 25, 50)]
    

    单元格样式

    from openpyxl.styles import Font, colors, Alignment
    
    # 下面的代码指定了等线24号,加粗斜体,字体颜色红色。直接使用cell的font属性,将Font对象赋值给它。
    bold_itatic_24_font = Font(name='等线', size=24, italic=True, color=colors.RED, bold=True)
    
    sheet['A1'].font = bold_itatic_24_font
    

    对齐方式

    也是直接使用cell的属性aligment,这里指定垂直居中和水平居中。除了center,还可以使用right、left等等参数。
    # 设置B1中的数据垂直居中和水平居中
    sheet['B1'].alignment = Alignment(horizontal='center', vertical='center')
    

    设置行高和列宽

    # 第2行行高
    sheet.row_dimensions[2].height = 40
    # C列列宽
    sheet.column_dimensions['C'].width = 30
    

    合并和拆分单元格

  • 所谓合并单元格,即以合并区域的左上角的那个单元格为基准,覆盖其他单元格使之称为一个大的单元格。

  • 相反,拆分单元格后将这个大单元格的值返回到原来的左上角位置。

      # 合并单元格, 往左上角写入数据即可
      sheet.merge_cells('B1:G1') # 合并一行中的几个单元格
      sheet.merge_cells('A1:C3') # 合并一个矩形区域中的单元格
    
  • 合并后只可以往左上角写入数据,也就是区间中:左边的坐标。

  • 如果这些要合并的单元格都有数据,只会保留左上角的数据,其他则丢弃。换句话说若合并前不是在左上角写入数据,合并后单元格中不会有数据。

  • 以下是拆分单元格的代码。拆分后,值回到A1位置。

      sheet.unmerge_cells('A1:C3')
    
  • 小案例

    import datetime
    from random import choice
    from time import time
    from openpyxl import load_workbook
    from openpyxl.utils import get_column_letter
    
    # 设置文件 mingc
    addr = "openpyxl.xlsx"
    # 打开文件
    wb = load_workbook(addr)
    # 创建一张新表
    ws = wb.create_sheet()
    # 第一行输入
    ws.append(['TIME', 'TITLE', 'A-Z'])
    
    # 输入内容(500行数据)
    for i in range(500):
        TIME = datetime.datetime.now().strftime("%H:%M:%S")
        TITLE = str(time())
        A_Z = get_column_letter(choice(range(1, 50)))
        ws.append([TIME, TITLE, A_Z])
    
    # 获取最大行
    row_max = ws.max_row
    # 获取最大列
    con_max = ws.max_column
    # 把上面写入内容打印在控制台
    for j in ws.rows:	# we.rows 获取每一行数据
        for n in j:
            print(n.value, end="\t")   # n.value 获取单元格的值
        print()
    # 保存,save(必须要写文件名(绝对地址)默认 py 同级目录下,只支持 xlsx 格式)
    wb.save(addr)
    

    案例

    1、 安装

    pip install openpyxl
    
    想要在文件中插入图片文件,需要安装pillow,安装文件:PIL-fork-1.1.7.win-amd64-py2.7.exe
    
     
    
    · font(字体类):字号、字体颜色、下划线等
    
    · fill(填充类):颜色等
    
    · border(边框类):设置单元格边框
    
    · alignment(位置类):对齐方式
    
    · number_format(格式类):数据格式
    
    · protection(保护类):写保护
    

    2、 创建一个excel 文件,并写入不同类的内容

    # -*- coding: utf-8 -*-
    
    from openpyxl import Workbook
    wb = Workbook()    #创建文件对象
    
    # grab the active worksheet
    ws = wb.active     #获取第一个sheet
    
    # Data can be assigned directly to cells
    ws['A1'] = 42      #写入数字
    ws['B1'] = "你好"+"automation test" #写入中文(unicode中文也可)
    
    # Rows can also be appended
    ws.append([1, 2, 3])    #写入多个单元格
    
    # Python types will automatically be converted
    import datetime
    import time
    ws['A2'] = datetime.datetime.now()    #写入一个当前时间
    #写入一个自定义的时间格式
    ws['A3'] =time.strftime("%Y年%m月%d日 %H时%M分%S秒",time.localtime())
    
    # Save the file
    wb.save("e:\\sample.xlsx")
    

    3、 创建sheet

    # -*- coding: utf-8 -*-
    from openpyxl import Workbook
    wb = Workbook()
    ws1 = wb.create_sheet("Mysheet")           #创建一个sheet
    
    ws1["A1"]=123.11
    ws1["B2"]="你好"
    d = ws1.cell(row=4, column=2, value=10)
    
    print ws1["A1"].value
    print ws1["B2"].value
    print d.value
    
    # Save the file
    wb.save("e:\\sample.xlsx")
    

    4、 操作单元格

    # -*- coding: utf-8 -*-
    from openpyxl import Workbook
    wb = Workbook()
    ws1 = wb.create_sheet("Mysheet")           #创建一个sheet
    
    ws1["A1"]=123.11
    ws1["B2"]="你好"
    d = ws1.cell(row=4, column=2, value=10)
    
    print ws1["A1"].value
    print ws1["B2"].value
    print d.value
    
    # Save the file
    wb.save("e:\\sample.xlsx")
    

    操作批量的单元格

    无论ws.rows还是ws.iter_rows都是一个对象

    除上述两个对象外 单行,单列都是一个元祖,多行多列是二维元祖

    # -*- coding: utf-8 -*-
    from openpyxl import Workbook
    wb = Workbook()
    
    ws1 = wb.create_sheet("Mysheet")           #创建一个sheet
    
    ws1["A1"]=1
    ws1["A2"]=2
    ws1["A3"]=3
    
    ws1["B1"]=4
    ws1["B2"]=5
    ws1["B3"]=6
    
    ws1["C1"]=7
    ws1["C2"]=8
    ws1["C3"]=9
    
    #操作单列
    print ws1["A"]
    for cell in ws1["A"]:
        print cell.value
    
    #操作多列,获取每一个值
    print ws1["A:C"]
    for column in ws1["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
    
    print "*"*50
    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 "*"*50
    #获取所有列
    print ws1.columns
    for col in ws1.columns:
        print col
    
    wb.save("e:\\sample.xlsx")
    

    使用百分数

    # -*- coding: utf-8 -*-
    from openpyxl import Workbook
    from openpyxl import load_workbook
    wb = load_workbook('e:\\sample.xlsx')
    wb.guess_types = True  # 如果等于False 结果会打印百分数
    ws=wb.active
    ws["D1"]="12%"
    print ws["D1"].value
    
    # Save the file
    wb.save("e:\\sample.xlsx")
    #结果会打印小数
    

    获取所有的行对象(常用于按行读excel)

    from openpyxl import load_workbook
    
    wb = load_workbook('1.xlsx')
    ws = wb.active
    for row in ws.iter_rows():
        print(tuple(map(lambda x: x.value, row)))
        
        # for i in row:
        #     print(i.value)
    

    获取所有的列对象(常用于按列读excel)

    from openpyxl import load_workbook
    
    wb = load_workbook('1.xlsx')
    ws = wb.active
    for row in ws.iter_cols():
        print(tuple(map(lambda x: x.value, row)))
    

    操作已经存在的文件(修改内容)

    from openpyxl import load_workbook
    
    wb = load_workbook('1.xlsx')
    wb.guess_types = True  # 猜测格式类型
    ws = wb.active
    print(ws['C2'])
    ws["D1"] = "12%"  # 直接修改
    
    wb.save("1.xlsx")
    # 注意如果原文件有一些图片或者图标,则保存的时候可能会导致图片丢失
    

    单元格类型

    from openpyxl import load_workbook
    import datetime
    
    wb = load_workbook('1.xlsx')
    
    ws = wb.active
    wb.guess_types = True
    
    ws["A1"] = datetime.datetime(2010, 7, 21)
    print(ws["A1"].number_format)
    
    ws["A2"] = "12%"
    print(ws["A2"].number_format)
    
    ws["A3"] = 1.1
    print(ws["A4"].number_format)
    
    ws["A4"] = "中国"
    print(ws["A5"].number_format)
    # Save the file
    wb.save("1.xlsx")
    #如果是常规,显示general,如果是数字,显示'0.00_ ',如果是百分数显示0%
    # 数字需要在Excel中设置数字类型,直接写入的数字是常规类型
    

    使用公式

    # -*- coding: utf-8 -*-
    from openpyxl import Workbook
    from openpyxl import load_workbook
    
    wb = load_workbook('e:\\sample.xlsx')
    ws1=wb.active
    
    ws1["A1"]=1
    ws1["A2"]=2
    ws1["A3"]=3
    
    ws1["A4"] = "=SUM(1, 1)"
    ws1["A5"] = "=SUM(A1:A3)"
    
    print(ws1["A4"].value)  #打印的是公式内容,不是公式计算后的值,程序无法取到计算后的值
    print(ws1["A5"].value)  #打印的是公式内容,不是公式计算后的值,程序无法取到计算后的值
    
    # Save the file
    wb.save("e:\\sample.xlsx")
    

    合并单元格

    需要先安装Pilow

    # -*- coding: utf-8 -*-
    from openpyxl import load_workbook
    from openpyxl.drawing.image import Image
    
    wb = load_workbook('e:\\sample.xlsx')
    ws1=wb.active
    
    img = Image('e:\\1.png')
    ws1.add_image(img, 'A1')
    
    # Save the file
    wb.save("e:\\sample.xlsx")
    

    隐藏单元格

    # -*- coding: utf-8 -*-
    from openpyxl import load_workbook
    from openpyxl.drawing.image import Image
    
    wb = load_workbook('e:\\sample.xlsx')
    ws1=wb.active
    
    ws1.column_dimensions.group('A', 'D', hidden=True)   #隐藏a到d列范围内的列
    #ws1.row_dimensions 无group方法
    # Save the file
    wb.save("e:\\sample.xlsx")
    

    设定一个表格区域,并设定表格的格式

    # -*- coding: utf-8 -*-
    from openpyxl import load_workbook
    from openpyxl import Workbook
    from openpyxl.worksheet.table import Table, TableStyleInfo
    
    wb = Workbook()
    ws = wb.active
    
    data = [
        ['Apples', 10000, 5000, 8000, 6000],
        ['Pears',   2000, 3000, 4000, 5000],
        ['Bananas', 6000, 6000, 6500, 6000],
        ['Oranges',  500,  300,  200,  700],
    ]
    
    # add column headings. NB. these must be strings
    ws.append(["Fruit", "2011", "2012", "2013", "2014"])
    for row in data:
        ws.append(row)
    
    tab = Table(displayName="Table1", ref="A1:E5")
    
    # Add a default style with striped rows and banded columns
    style = TableStyleInfo(name="TableStyleMedium9", showFirstColumn=True,
                           showLastColumn=True, showRowStripes=True, showColumnStripes=True)
    #第一列是否和样式第一行颜色一行,第二列是否···
    #是否隔行换色,是否隔列换色
    tab.tableStyleInfo = style
    ws.add_table(tab)
    
    # Save the file
    wb.save("e:\\sample.xlsx")
    

    给单元格设定字体颜色

    # -*- coding: utf-8 -*-
    from openpyxl import Workbook
    from openpyxl.styles import colors
    from openpyxl.styles import Font
    
    wb = Workbook()
    ws = wb.active
    
    a1 = ws['A1']
    d4 = ws['D4']
    ft = Font(color=colors.RED)  # color="FFBB00",颜色编码也可以设定颜色
    a1.font = ft
    d4.font = ft
    
    # If you want to change the color of a Font, you need to reassign it::
    #italic 倾斜字体
    a1.font = Font(color=colors.RED, italic=True) # the change only affects A1
    a1.value = "abc"
    
    # Save the file
    wb.save("e:\\sample.xlsx")
    

    设定字体和大小

    # -*- coding: utf-8 -*-
    from openpyxl import Workbook
    from openpyxl.styles import colors
    from openpyxl.styles import Font
    
    wb = Workbook()
    ws = wb.active
    
    a1 = ws['A1']
    d4 = ws['D4']
    a1.value = "abc"
    
    from openpyxl.styles import Font
    from copy import copy
    
    ft1 = Font(name=u'宋体', size=14)
    ft2 = copy(ft1)   #复制字体对象
    ft2.name = "Tahoma"
    
    print ft1.name
    print ft2.name
    print ft2.size # copied from the
    
    a1.font = ft1
    # Save the file
    wb.save("e:\\sample.xlsx")
    

    设定行和列的字体

    # -*- coding: utf-8 -*-
    from openpyxl import Workbook
    from openpyxl.styles import Font
    wb = Workbook()
    ws = wb.active
    
    col = ws.column_dimensions['A']
    col.font = Font(bold=True)   #将A列设定为粗体
    row = ws.row_dimensions[1]
    row.font = Font(underline="single")  #将第一行设定为下划线格式
    
    # Save the file
    wb.save("e:\\sample.xlsx")
    

    设定单元格的边框、字体、颜色、大小和边框背景色

    # -*- coding: utf-8 -*-
    from openpyxl import Workbook
    from openpyxl.styles import Font
    from openpyxl.styles import NamedStyle, Font, Border, Side,PatternFill
    
    wb = Workbook()
    ws = wb.active
    
    highlight = NamedStyle(name="highlight")
    highlight.font = Font(bold=True, size=20,color= "ff0100")
    highlight.fill = PatternFill("solid", fgColor="DDDDDD")#背景填充
    bd = Side(style='thick', color="000000")
    highlight.border = Border(left=bd, top=bd, right=bd, bottom=bd)
    
    print dir(ws["A1"])
    ws["A1"].style =highlight
    
    # Save the file
    wb.save("e:\\sample.xlsx")
    

    常用的样式和属性设置

    # -*- coding: utf-8 -*-
    from openpyxl import Workbook
    from openpyxl.styles import Font
    from openpyxl.styles import NamedStyle, Font, Border, Side,PatternFill
    from openpyxl.styles import PatternFill, Border, Side, Alignment, Protection, Font
    
    wb = Workbook()
    ws = wb.active
    
    ft = Font(name=u'微软雅黑',
        size=11,
        bold=False,
        italic=False,
        vertAlign=None,
        underline='none',
        strike=False,
        color='FF000000')
    
    fill = PatternFill(fill_type="solid",
        start_color='FFEEFFFF',
        end_color='FF001100')
    
    #边框可以选择的值为:'hair', 'medium', 'dashDot', 'dotted', 'mediumDashDot', 'dashed', 'mediumDashed', 'mediumDashDotDot', 'dashDotDot', 'slantDashDot', 'double', 'thick', 'thin']
    #diagonal 表示对角线
    bd = Border(left=Side(border_style="thin",
                  color='FF001000'),
        right=Side(border_style="thin",
                   color='FF110000'),
        top=Side(border_style="thin",
                 color='FF110000'),
        bottom=Side(border_style="thin",
                    color='FF110000'),
        diagonal=Side(border_style=None,
                      color='FF000000'),
        diagonal_direction=0,
        outline=Side(border_style=None,
                     color='FF000000'),
        vertical=Side(border_style=None,
                      color='FF000000'),
        horizontal=Side(border_style=None,
                       color='FF110000')
                    )
    
    alignment=Alignment(horizontal='general',
            vertical='bottom',
            text_rotation=0,
            wrap_text=False,
            shrink_to_fit=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 ="zeke"
    
    # Save the file
    wb.save("e:\\sample.xlsx")
    

    插入图片

    from openpyxl import load_workbook
    from openpyxl.drawing.image import Image
    
    wb = load_workbook('1.xlsx')
    ws1 = wb.active
    
    img = Image(r'C:\Users\EDY\Desktop\1654138574(1).jpg')
    img.width, img.height = 50, 50
    
    ws1.add_image(img, 'F1')
    # 第2行行高
    ws1.row_dimensions[2].height = 40
    # C列列宽
    ws1.column_dimensions['C'].width = 30
    
    wb.save("1.xlsx")
    

    样式详解

    字体样式

    from openpyxl import Workbook
    from openpyxl.styles import Font
    
    wb = Workbook()
    ws = wb.active
    
    # 默认字体样式
    ws["A1"] = "A1"
    
    # 自定义字体样式
    ws["B2"] = "B2"
    font = Font(
        name="微软雅黑",   # 字体
        size=15,         # 字体大小
        color="0000FF",  # 字体颜色,用16进制rgb表示
        bold=True,       # 是否加粗,True/False
        italic=True,     # 是否斜体,True/False
        strike=None,     # 是否使用删除线,True/False
        underline=None,  # 下划线, 可选'singleAccounting', 'double', 'single', 'doubleAccounting'
    )
    ws["B2"].font = font
    
    wb.save("./test.xlsx")
    

    行列宽高

    from openpyxl import Workbook
    wb = Workbook()
    ws = wb.active
    
    ws.row_dimensions[2].height = 30  # 设置第2行高度为30
    ws.column_dimensions["B"].width = 30  # 设置B列宽度为30
    
    wb.save("./test.xlsx")
    

    对齐方式

    from openpyxl import Workbook
    from openpyxl.styles import Border, Side
    
    wb = Workbook()
    ws = wb.active
    
    ws["B2"] = "B2"
    
    side = Side(
        style="medium",  # 边框样式,可选dashDot、dashDotDot、dashed、dotted、double、hair、medium、mediumDashDot、mediumDashDotDot、mediumDashed、slantDashDot、thick、thin
        color="ff66dd",  # 边框颜色,16进制rgb表示
    )
    
    ws["B2"].border = Border(
        top=side,  # 上
        bottom=side,  # 下
        left=side,  # 左
        right=side,  # 右
        diagonal=side  # 对角线
    )
    
    wb.save("./test.xlsx")
    

    边框

    from openpyxl import Workbook
    from openpyxl.styles import Border, Side
    
    wb = Workbook()
    ws = wb.active
    
    ws["B2"] = "B2"
    
    side = Side(
        style="medium",  # 边框样式,可选dashDot、dashDotDot、dashed、dotted、double、hair、medium、mediumDashDot、mediumDashDotDot、mediumDashed、slantDashDot、thick、thin
        color="ff66dd",  # 边框颜色,16进制rgb表示
    )
    
    ws["B2"].border = Border(
        top=side,  # 上
        bottom=side,  # 下
        left=side,  # 左
        right=side,  # 右
        diagonal=side  # 对角线
    )
    
    wb.save("./test.xlsx")
    

    填充和渐变

    from openpyxl import Workbook
    from openpyxl.styles import PatternFill, GradientFill
    
    wb = Workbook()
    ws = wb.active
    
    ws["B2"] = "B2"
    
    fill = PatternFill(
        patternType="solid",  # 填充类型,可选none、solid、darkGray、mediumGray、lightGray、lightDown、lightGray、lightGrid
        fgColor="F562a4",  # 前景色,16进制rgb
        bgColor="0000ff",  # 背景色,16进制rgb
        # fill_type=None,  # 填充类型
        # start_color=None, # 前景色,16进制rgb
        # end_color=None    # 背景色,16进制rgb
    )
    ws["B2"].fill = fill
    ws["B3"].fill = GradientFill(
        degree=60,  # 角度
        stop=("000000", "FFFFFF")  # 渐变颜色,16进制rgb
    )
    
    wb.save("./test.xlsx")
    

    案例

    from openpyxl import Workbook
    from openpyxl.styles import Border, Side, colors, borders, Font, Alignment
    
    
    class ExportExcel(object):
        '''导出excel'''
    
        def __init__(self):
            self._wb = Workbook()
            self._border = Border(  # 边框
                top=Side(style=borders.BORDER_THIN, color=colors.BLACK),
                bottom=Side(style=borders.BORDER_THIN, color=colors.BLACK),
                left=Side(style=borders.BORDER_THIN, color=colors.BLACK),
                right=Side(style=borders.BORDER_THIN, color=colors.BLACK)
            )
            self._font = Font(bold=True, size=10)  # 字体
            self._alignment = Alignment(horizontal='center', vertical='center')  # 居中
    
        def jibenxinxi(self):
            '''基本信息'''
            sheet = self._wb.create_sheet('基本信息', 0)
            for index, row in enumerate(sheet['A1:L16']):
                sheet.row_dimensions[index + 1].height = 35  # 行高
                for info in row:
                    info.border = self._border
                    info.alignment = self._alignment
                    info.font = self._font
                    info.alignment = self._alignment
    
            sheet.merge_cells('A1:L1')
            sheet['A1'] = '教员基本情况'
    
            sheet['A2'] = '姓名'
            sheet.merge_cells('A2:C2')
            sheet['D2'] = 'xx'
            sheet.merge_cells('D2:F2')
    
            sheet['G2'] = '性别'
            sheet['H2'] = 'xx'
    
            sheet['I2'] = '民族'
            sheet['J2'] = 'xx'
    
            sheet['K2'] = '籍贯'
            sheet['L2'] = 'xx'
            # ----------------------------------------
    
            sheet['A3'] = '出生年月'
            sheet.merge_cells('A3:C3')
            sheet['D3'] = 'xx'
            sheet.merge_cells('D3:F3')
    
            sheet['G3'] = '工作年月'
            sheet['H3'] = 'xx'
    
            sheet['I3'] = '任教年月'
            sheet['J3'] = 'xx'
    
            sheet['K3'] = '出生地'
            sheet['L3'] = 'xx'
            # --------------------------------------
    
            sheet['A4'] = '人员类型'
            sheet.merge_cells('A4:C4')
            sheet['D4'] = 'xx'
            sheet.merge_cells('D4:F4')
    
            sheet['G4'] = '职务'
            sheet['H4'] = 'xx'
    
            sheet['I4'] = '政治面貌'
            sheet['J4'] = 'xx'
    
            sheet['K4'] = '婚姻状况'
            sheet['L4'] = 'xx'
    
            self._wb.save(r'C:\Users\EDY\Desktop\1.xlsx')
    
    
    # r = ExportExcel()
    # r.jibenxinxi()
    
    物联沃分享整理
    物联沃-IOTWORD物联网 » Python–openpyxl详解

    发表评论