1.安装openpyxl
pip install openpyxl
2.创建表格
from openpyxl import Workbook
# 创建一个对象
wb = Workbook()
# 使用默认的Sheet
ws = wb.active
# 添加一行数据
ws.append([1, 2, 3])
# 再创建一张表单 命名为MySheet2
ws2 = wb.create_sheet('MySheet2')
# 给MySheet2 添加一行数据
ws2.append([4, 5, 6])
# 最后保存文档 命名为Demo-01.xlsx
wb.save('Demo-01.xlsx')
3.加载已有的表格
from openpyxl import load_workbook
# 加载刚刚创建的表格
wb = load_workbook('Demo-01.xlsx')
# 打印当前表格有几张表 [<Worksheet "Sheet">, <Worksheet "MySheet2">]
print(wb.worksheets)
# 选择Sheet
ws1 = wb['Sheet']
# 添加一行数据
ws1.append([4, 5, 6])
# 选择MySheet2 添加一行数据
ws2 = wb['MySheet2']
ws2.append([7, 8, 9])
# 保存
wb.save('Demo-01.xlsx')
4.生成批量数据
import random
from openpyxl import load_workbook
wb = load_workbook('Demo-01.xlsx')
# 第二种选择表格的方法 注意与3中的区别
sheets = wb.worksheets
sheets1 = sheets[0]
for i in range(1, 10):
for j in range(1, 10):
sheets1.cell(row=i, column=j, value=random.randint(0, 10))
wb.save('Demo-01.xlsx')
生成的数据如下:
5.查询数据
from openpyxl import load_workbook
wb = load_workbook('Demo-01.xlsx')
sheets = wb.worksheets
sheets1 = sheets[0]
for row in sheets1.rows:
for i in range(0, 9):
print(row[i].value, end=' ')
print()
wb.save('Demo-01.xlsx')
这里将数据按行输出一下,如下所示:
6.修改指定单元格的内容
from openpyxl import load_workbook
wb = load_workbook('Demo-01.xlsx')
sheets = wb.worksheets
sheet1 = sheets[0]
# 将第8行第8列的数据改为Hello
sheet1['H8'] = "Hello"
# 将第9行9列的数据改为World
sheet1['I9'] = "World!"
wb.save('Demo-01.xlsx')
修改之后的数据如下所示:
总结:时间原因,本文仅仅是介绍openpyxl的基本使用,后续将会深入介绍!