Home > Article > Backend Development > A case of Python operating excel files
This article mainly introduces the example code of using Python to operate excel files. Friends who need it can refer to
The class library used
pip install openpyxl
Operation implementation
##•Workbook operation
# coding: utf-8 from openpyxl import Workbook # 创建一个excel工作簿 wb = Workbook() # 打开一个工作簿 wb = load_workbook('test.xlsx') # 保存工作簿到文件 wb.save('save.xlsx')
•Worksheet operations
# 获得当前的工作表对象 ws = wb.active # 通过工作表名称得到工作表对象 ws = wb.get_sheet_by_name('sheet') # 获取工作簿的所有工作表对象列表 ws = wb。get_sheet_names() # 在工作簿末尾创建一个工作表 ws = wb.create_sheet() # 在第一个位置创建一个工作表 ws = wb.create_sheet(0) # 修改工作表名称 ws.title = "new sheet"
•Data operations
# 使用一个单元格 # 根据索引获得单元格内容 res = ws['A4'] # 使用cell方法获取单元格 res = ws.cell('A4') # 或 res = ws.cell(row = 4, column = 1) # 创建100*100的单元格 for i in range(1,101) for j in range (1,101) ws.cell(row = i, column = j) # 使用切片获取多个单元格 cells = ws['A1':'d4'] # 使用iter_rows()方法获得行和列 t = touple(ws.iter_rows('A1:D4')) # 使用rows获取所有行 t = ws.rows() # 使用columns()获取所有列 t = ws.columns()Summary
The above is the detailed content of A case of Python operating excel files. For more information, please follow other related articles on the PHP Chinese website!