赞
踩
openpyxl 模块:可以读取和修改 Excel 电子表格文件
软件名及软件下载地址
LibreOffice Calc
Apache OpenOffice - Official Site - The Free and Open Productivity Suite
OpenOffice Calc
Home | LibreOffice - Free Office Suite - Based on OpenOffice - Compatible with Microsoft
一个 Excel 电子表格文档称为一个工作簿 - - - 扩展名为.xlsx
每个工作簿可以包含多个表(也称为工作表)
用户当前查看的表(或关闭 Excel 前最后查看的表),称为活动表
pip install openpyxl
openpyxl - A Python library to read/write Excel 2010 xlsx/xlsm files
openpyxl.load_workbook()
函数import openpyxl
# 打开 Excel 文件
wb = openpyxl.load_workbook('example.xlsx')
type(wb) # <class 'openpyxl.workbook.workbook.Workbook'>
sheetnames
wb.sheetnames # ['Sheet1', 'Sheet2', 'Sheet3']
# 选择工作表
sheet = wb['Sheet3']
print(sheet) # <Worksheet "Sheet3">
type(sheet) # <class 'openpyxl.worksheet.worksheet.Worksheet'>
sheet.title # 'Sheet3'
anotherSheet = wb.active # 活动表
anotherSheet # <Worksheet "Sheet1">
有了 Worksheet 对象后,就可以按名字访问 Cell 对象
row
行、column
列 和 coordinate
坐标 属性,提供该单元格的位置信息
import openpyxl wb = openpyxl.load_workbook('example.xlsx') sheet = wb.get_sheet_by_name('Sheet1') sheet['A1'] # <Cell Sheet1.A1> sheet['A1'].value # datetime.datetime(2015, 4, 5, 13, 34, 2) c = sheet['B1'] c.value # 'Apples' 'Row ' + str(c.row) + ', Column ' + str(c.column) + ' is ' + c.value # 'Row 1, Column 2 is Apples' 'Cell ' + c.coordinate + ' is ' + c.value # 'Cell B1 is Apples' sheet['C1'].value # 73 sheet.cell(row=1, column=2) # <Cell Sheet1.B1> for i in range(1, 8, 2): print(i, sheet.cell(row=i, column=2).value) # 1 Apples # 3 Pears # 5 Apples # 7 Strawberries
max_row
获取工作表总行数,max_column
总列数
sheet.max_row # 7
sheet.max_column # 3
import openpyxl import openpyxl.utils # 列字母转换为数字索引 col_letter = 'D' col_num = openpyxl.utils.column_index_from_string(col_letter) print(f"{ col_letter} 对应的数字索引为:{ col_num}") # D 对应的数字索引为:4 # 数字索引转换为列字母 col_num = 4 col_letter = openpyxl.utils.get_column_letter(col_num) print(f"{ col_num} 对应的列字母为:{ col_letter}") # 4 对应的列字母为:D
from openpyxl.utils import column_index_from_string,get_column_letter
column_index_from_string('aa') # 27
可以将 Worksheet 对象切片
,取得电子表格中一行、一列或一个矩形区域中的所有Cell 对象。然后可以循环遍历这个切片中的所有单元格
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。