Openpyxl 是用来读写Excel 2010 xlsx/xlsm/xltx/xltm文件的库。
Documentations of Openpyxl on readthedocs.io: https://openpyxl.readthedocs.io/en/stable/
Security
By default openpyxl does not guard against quadratic blowup or billion laughs xml attacks. To guard against these attacks install defusedxml.
Openpyxl不兼容旧版的xls文件。
~$: pip install openpyxl
import openpyxl
workbook = openpyxl.Workbook()
xlsx文件工作表的索引是从0开始的。
# 第一个工作表后面创建工作表
sheet_name = ‘sheet1’
sheet = workbook.create_sheet(sheet_name)
# Equal to the following
# 工作表名称列表
sheet_names = workbook.get_sheet_names()
sheet = workbook.create_sheet(sheet_name, index=len(sheet_names))
# 第一个工作表前创建
sheet = workbook.create_sheet(sheet_name, 0)
# sheet = workbook.create_sheet(sheet_name, index=0)
# 使用新建xlsx文件后活动状态的空白工作表
sheet = workbook.active
sheet.title = sheet_name
excel_file = ‘excel1.xlsx’
workbook.save(excel_file)
workbook.close()
excel_file = ‘excel1.xlsx’
workbook = openpyxl.load_workbook(excel_file)
# 使用当前活动工作表
sheet = workbook.active
# 使用指定已存在的工作表
sheet_name = ‘sheet1’
sheet = workbook.get_sheet_by_name(sheet_name)
# 判断工作表是否已存在
sheet_names = workbook.get_sheet_names()
sheet_existed = sheet_name in sheet_names
xlsx文件工作表的单元格索引是从1开始的。
# data = [[‘Name’, ‘Sex’, ‘Age’],
# [‘Jack’, ‘M’, ‘20’], [‘Ross’, ‘F’, ‘19’], [‘Peter’, ‘M’, ‘25’]]
data = [[‘Jack’, ‘M’, ‘20’], [‘Ross’, ‘F’, ‘19’], [‘Peter’, ‘M’, ‘25’]]
for row, item in enumerate(data):
for column, cell in enumerate(item):
sheet.cell(row=row + 1, column=column + 1, value=cell)
# Append a empty row in sheet
sheel.cell([])
workbook.remove(sheet_name)
# workboo.remove(worksheet=sheet_name)
def save_to_excel(data, excel_file, sheet_name='sheet1'):
# data is like [[row1_column1, row1_column2, row1_column3],
# [row2_column1, row2_column2, row2_column3],
# [...], ...]
if os.path.exists(excel_file):
workbook = load_excel(excel_file)
else:
workbook = openpyxl.Workbook()
sheet_names = workbook.get_sheet_names()
if sheet_name in sheet_names:
sheet = workbook.get_sheet_by_name(sheet_name)
else:
sheet = workbook.create_sheet(sheet_name)
# sheet = workbook.create_sheet(sheet_name, len(workbook.get_sheet_names()))
# sheet = workbook.active
# sheet.title = sheet_name
for row, item in enumerate(data):
for column, cell in enumerate(item):
sheet.cell(row=row + 1, column=column + 1, value=cell)
workbook.save(excel_file)
workbook.close()