openpyxl使用文档

安装openpyxl

pip install openpyxl

创建文档

from openpyxl import Workbook
wb=Workbook()

创建工作簿

# 方法一
ws = wb.active
ws.title='New Title'
# 方法二
ws1 = wb.create_sheet('Mysheet') # 默认插入在最后
ws2 = wb.create_sheet('Mysheet',0) # 插入在最前
ws3 = wb.create_sheet('Mysheet',-1) # 插入在倒数第二的位置

复制工作簿

source = wb.active
target=wb.copy_worksheet(source)

保存到文件

wb.save('xxxxx.xlsx')

读取文档

import openpyxl
wb = openpyxl.load_workbook("测试数据.xlsx")

读工作簿

# 两种读法,哪种能读出来就用哪种,返回列表
sheetnames=wb.sheetnames or wb.get_sheet_names()
# ['sheet1','sheet2']
for sheet in wb:
    print(sheet.title)
    # sheet1
    # sheet2

读取数据

单个数据读取

# example.cell(行,列).value
example.cell(2,5).value

按行读取

# 按行读取 values_only 为True 返回内容,为 False 为内存地址
for row in example.iter_rows(values_only=True):
    print(row)
    # 返回一个元组
    # (1183089473225, '合肥', '温州', datetime.datetime(2020, 6, 25, 8, 16, 26), ' 温州市到达【温州邮件处理中心】')
    nums,addr,addrs,datetime,abd=row
    print(nums,addr,addrs,datetime,abd)
    # 9976400679821 银川 南京 2020-03-18 02:58:38  兰州市离开【兰州邮件处理中心】下一站【乌鲁木齐邮件处理中心】(经转)

按列读取

for col in example.iter_cols(values_only=True):
    print(col)
    # 返回多个元组
    # (xxx,xxx,xxx,xxx,xxx)
    # (xxx,xxx,xxx,xxx,xxx)
    # (xxx,xxx,xxx,xxx,xxx)
    # (xxx,xxx,xxx,xxx,xxx)
    # (xxx,xxx,xxx,xxx,xxx)
    

写入/改变数据

# 第一种方法
c=example.cell(2,5)
print(c.value)
# xxxxxxxx
c.value=100
print(c.value)
# 100
# 第二种方法
wb.cell(row=1,column=1,value=10) # row 行标,column 列标,value 写入的内容,注意,行标和列标以1开始

写入数据例子

# 数据例子
a =[
    [1,2,3,4,5,6,7,8,9],
    ["a","b","c","d","e","f","g","h","i"],
    ["j","k","l","m","n","o","p","q","r"],
    ["s","t","u","v","w","x","y","z",1]
    ]
from openpyxl import Workbook

wb=Workbook()
ws=wb.active
# 创建工作簿
ws.title="Mysheet"
for row in range(len(a)):
    for col in range(len(a[row])):
        ws.cell(row+1,col+1,a[row][col])
wb.save('bbb.xlsx')

你可能感兴趣的:(openpyxl使用文档)