当前位置:   article > 正文

python-处理 Excel 电子表格-openpyxl模块_import openpyxl

import openpyxl

前言

openpyxl 模块:可以读取和修改 Excel 电子表格文件

一个 Excel 电子表格文档称为一个工作簿 - - - 扩展名为.xlsx
每个工作簿可以包含多个表(也称为工作表)
用户当前查看的表(或关闭 Excel 前最后查看的表),称为活动表

一、安装openpyxl模块

pip install openpyxl
  • 1

openpyxl - A Python library to read/write Excel 2010 xlsx/xlsm files

二、读取 Excel 文档

1.用 openpyxl 模块打开 Excel 文档 openpyxl.load_workbook()函数

import openpyxl

# 打开 Excel 文件
wb = openpyxl.load_workbook('example.xlsx')
type(wb)	# <class 'openpyxl.workbook.workbook.Workbook'>
  • 1
  • 2
  • 3
  • 4
  • 5

2.从工作簿中取得工作表的名称 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">
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

3.从表中取得单元格

有了 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
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

max_row获取工作表总行数,max_column总列数

sheet.max_row		# 7
sheet.max_column	# 3
  • 1
  • 2

在这里插入图片描述

4.列字母和数字之间的转换

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
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
from openpyxl.utils import column_index_from_string,get_column_letter
column_index_from_string('aa')	# 27
  • 1
  • 2

5.从表中取得行和列

可以将 Worksheet 对象切片,取得电子表格中一行、一列或一个矩形区域中的所有Cell 对象。然后可以循环遍历这个切片中的所有单元格

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/834396
推荐阅读
相关标签
  

闽ICP备14008679号