文章目录
- 1 概述
- 2 常用对象
-
- 2.1 工作簿 workbook
- 2.2 工作表 sheet
- 2.3 单元格 cell
- 3 示例
-
1 概述
import openyxl
非内置模块,需安装:pip install openpyxl
适用对象:Excel 2007 及以上 (*.xlsx)
2 常用对象
2.1 工作簿 workbook
import openpyxl
wb = openpyxl.Workbook()
file_name = '2.xlsx'
wb.save(file_name)
lwb = openpyxl.load_workbook(file_name)
print(lwb.active)
print(lwb.read_only)
print(lwb.encoding)
print(lwb.properties)
print('-------- 分割线 1 --------')
print(lwb.worksheets)
print(lwb.sheetnames)
print(lwb['Sheet'])
print(lwb.create_sheet('Sheet1'))
print(lwb.copy_worksheet(lwb['Sheet1']))
lwb.save(file_name)
2.2 工作表 sheet
import openpyxl
file_name = '1.xlsx'
lwb = openpyxl.load_workbook(file_name)
sheet = lwb['Sheet']
sheet.append(['姓名', '性别', '年龄'])
sheet.append(['张三', '女', 18])
sheet.append(['李四', '男', 19])
sheet.append(['王五', '女', 20])
sheet.append({'A': 'A列', 'B': 'B列'})
sheet.delete_rows(3)
sheet.delete_cols(3)
print(sheet.title)
print(sheet.dimensions)
print(sheet.rows)
print(sheet.min_row)
print(sheet.max_row)
print(sheet.columns)
print(sheet.min_column)
print(sheet.max_column)
print('--------- 分割线 1 ---------')
print(sheet.values)
print(sheet.iter_rows())
print(sheet.iter_cols())
print(sheet['A1'].value)
print('--------- 分割线 2 ---------')
for row in sheet.iter_rows():
for cell in row:
print(cell.row, cell.column, cell.value)
lwb.save(file_name)
2.3 单元格 cell
import openpyxl
file_name = '1.xlsx'
lwb = openpyxl.load_workbook(file_name)
sheet = lwb['Sheet']
cell1 = sheet['A1']
cell2 = sheet.cell(1, 1)
print(cell1.value)
print(cell2.value)
cellList = sheet['A1:B2']
for item in cellList:
for cell in item:
print(cell.row, cell.column, cell.value)
lwb.save(file_name)
3 示例
3.1 遍历 Excel
import openpyxl
def read_excel(file_name):
"""
遍历 sheet 中的数据
:param file_name: 文件名
"""
lwb = openpyxl.load_workbook(file_name)
sheets = lwb.worksheets
print(sheets)
for sheet in sheets:
print(f'开始遍历:{sheet},最大行数:{sheet.max_row},最大列数:{sheet.max_column}')
for row in sheet.iter_rows():
for cell in row:
print(cell.row, cell.column, cell.value)
print(f'结束遍历:{sheet}')
if __name__ == '__main__':
file_name = '1.xlsx'
read_excel(file_name)