利用Python openpyxl操作Excel
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all" #全部行都能输出
import warnings
warnings.filterwarnings('ignore')
Excel基本概念
- 工作簿:一个Excel电子表格文档,扩展名.xlsx
- 工作表:一个工作簿最多可以包含255张工作表
- 活动表:用户当前查看或关闭Excel前最后退出的表
- 列:默认从A开始,行:默认从1开始
- 单元格:行列交叉的方格为单元格
安装openpyxl模块
# pip install openpyxl
import openpyxl
pip show openpyxl #查看包的版本
读取Excel文档
用openpyxl模块打开Excel文档
wb = openpyxl.load_workbook(r"C:\\Users\\Administrator\\example.xlsx") # wb means workbook
type(wb)
import os
os.getcwd() #获取当前工作路径
# os.chdir() #更改当前工作路径
从工作簿中取得工作表
wb.get_sheet_names()
sheet3 = wb.get_sheet_by_name('Sheet3') #get sheet by name
type(sheet3) #the type of sheet3 is a worksheet
sheet3.title #view the title of sheet
anotherSheet = wb.get_active_sheet() #get active sheet
anotherSheet.title #活动单元格的title
从表中取得单元格
import openpyxl
wb = openpyxl.load_workbook('example.xlsx')
sheet1 = wb.get_sheet_by_name("Sheet1")
sheet1['A1'] # Cell 提取单元格
sheet1['A1'].value #单元格的数据类型和内容
sheet1['A1'].row #单元格所在的行
sheet1['A1'].column #单元格所在的列
sheet1['A1'].coordinate #单元格所在的列
sheet1.cell(row=1,column=2) #提取第1行、第2列的单元格
sheet1.cell(row=1,column=2).value #提取第1行、第2列的单元格的值
for i in range(1,8,2):
print(i,sheet1.cell(row=i,column=2).value)
import openpyxl
wb = openpyxl.load_workbook(r"C:\\Users\\Administrator\\example.xlsx")
sheet1 = wb.get_sheet_by_name('Sheet1')
sheet1.max_row
sheet1.max_column
列字母和数字之间的转化
import openpyxl
from openpyxl.utils import get_column_letter,column_index_from_string
get_column_letter(1)
get_column_letter(100)
column_index_from_string('A')
column_index_from_string('AA')
从表中取得行和列
import openpyxl
wb = openpyxl.load_workbook(r"C:\\Users\\Administrator\\example.xlsx")
sheet1 = wb.get_sheet_by_name('Sheet1')
tuple(sheet1['A1':'C3']) #每一行单独成tuple的一个元素
list(sheet1['A1':'C3']) #每一行单独成list的一个元素
for rowOfCellObjects in sheet1['A1':'C3']: #打印区域
for cellObj in rowOfCellObjects:
print(cellObj.coordinate,cellObj.value)
print('---End of Row---')
import openpyxl
wb = openpyxl.load_workbook(r"C:\\Users\\Administrator\\example.xlsx")
sheet1 = wb.get_active_sheet()
for cellObj in list(sheet1.columns)[1]: #打印单列
print(cellObj.value)
小结
- 导入openpyxl模块
- 调用openpyxl.load_workbook()函数
- 取得Workbook对象
- 调用get_active_sheet()或get_sheet_by_name()工作簿方法
- 使用索引或工作表的cell()方法,Cell()方法带上row和column参数
- 取得Cell对象
- 读取Cell对象的value/row/column/coordinate属性
项目:从Excel中读取数据
读取电子表格数据
import openpyxl,pprint
print("Opening workbook ...")
wb = openpyxl.load_workbook(r"C:\\Users\\Administrator\\censuspopdata.xlsx") #Workbook对象
sheet = wb.get_sheet_by_name('Population by Census Tract') #Worksheet对象
countyData = {}
#ToDo: Fill in countyData with each county's population and tracts.
print("Reading row...")
填充数据结构
for row in range(2,sheet.max_row+1):
#Each row in the spreadsheet has data for one census tract.
State = sheet['B'+str(row)].value
County = sheet['C'+str(row)].value
Pop = sheet['D'+str(row)].value
# Make sure the key for this State exists.
countyData.setdefault(State,{})
#Make sure the key for this County in this state exists.
countyData[State].setdefault(County,{'tracts':0,'pop':0})
# Each row represents one census tractso increment by one.
countyData[State][County]['tracts'] += 1
#Increase the county pop by the pop in this census tract.
countyData[State][County]['pop'] += int(Pop)
将程序结果写入文件
# Open a new text file and write the contents of countyData to it.
print("Writing results")
resultFile = open('census2010.py','w')
resultFile.write('allData = '+pprint.pformat(countyData))
resultFile.close()
print("Done")
# 调用已经存储好的census2010.py文件查看结果
import census2010
anchoragePop = census2010.allData['AK']['Anchorage']['pop']
print("The 2010 population of Anchorage was " + str(anchoragePop))
类似程序的思想(略)
写入Excel文档
创建并保存Excel文档
import openpyxl
wb = openpyxl.Workbook() #创建空对象
wb.get_sheet_names() #查看空对象的sheet
sheet = wb.get_active_sheet() #获取当前活动工作表
sheet.title
sheet.title = 'Spam Bacon Eggs Sheet' #修改当前工作表的title
wb.get_sheet_names() #查看已修改的活动工作表title
import openpyxl
wb = openpyxl.load_workbook('example.xlsx')
sheet = wb.get_active_sheet()
sheet.title = 'Spam Spam Spam'
wb.save('example_copy.xlsx') #保存修改工作表名的拷贝
创建和删除工作表
import openpyxl
wb = openpyxl.Workbook()
wb.get_sheet_names()
wb.create_sheet()
wb.get_sheet_names()
wb.create_sheet(index=0,title='First Sheet')
wb.get_sheet_names()
wb.create_sheet(index=2,title = 'Middle Sheet')
wb.get_sheet_names
wb.remove_sheet(wb.get_sheet_by_name('Middle Sheet'))
wb.remove_sheet(wb.get_sheet_by_name('Sheet1'))
wb.get_sheet_names()
['First Sheet', 'Sheet']
将值写入单元格
import openpyxl
wb = openpyxl.Workbook()
sheet = wb.get_sheet_by_name('Sheet')
sheet['A1'] = 'Hello World'
sheet['A1'].value
项目:更新一个电子表格
利用更新信息建立数据结构
import openpyxl
wb = openpyxl.load_workbook('produceSales.xlsx')
sheet = wb.get_sheet_by_name('Sheet')
# the produce types and their updated prices
price_updates = {'Garlic':3.07,'Celery':1.19,'Lemon':1.27}
#ToDo:Loop through the rows and update the prices.
检查所有行,更新不正确的价格
for rowNum in range(2,sheet.max_row+1): #the first row is heading, skip it
produceName = sheet.cell(row=rowNum,column=1).value
if produceName in price_updates:
sheet.cell(row=rowNum,column=2).value = price_updates[produceName]
wb.save('updatedProduceSales.xlsx')
类似程序的思想(从略)
设置单元格的字体风格
from openpyxl.styles import Font
wb = openpyxl.Workbook()
sheet = wb.get_sheet_by_name('Sheet')
italic24Font = Font(size = 24, italic = True)
sheet['A1'].font = italic24Font
sheet['A1'] = 'Hello world!'
wb.save('styled.xlsx')
Font对象
import openpyxl
from openpyxl.styles import Font
wb = openpyxl.Workbook()
sheet = wb.get_sheet_by_name('Sheet')
fontobj1 = Font(name='Times New Roman',italic=True) #name 字体 size 字号 bold 是否加粗 italic 是否斜体
sheet['A1'].font = fontobj1
sheet['A1'] = 'Bold Times New Roman'
fontobj2 = Font(size=24,italic=True)
sheet['B3'].font = fontobj2
sheet['B3']= '23 pt Italic'
wb.save('styles.xlsx') #默认size 11 name Calibri
公式
import openpyxl
wb = openpyxl.Workbook()
sheet = wb.get_active_sheet()
sheet['A1'] = 200
sheet['A2'] = 300
sheet['A3'] = '=SUM(A1:A2)'
wb.save('writeFormula.xlsx')
import openpyxl
wb = openpyxl.load_workbook('writeFormula.xlsx')
sheet = wb.get_active_sheet()
sheet['A3'].value
import openpyxl
wbDataonly = openpyxl.load_workbook('writeFormula.xlsx',data_only=True)
sheet1 = wbDataonly.get_active_sheet()
sheet1['A3'].value #此处需要手动打开一次.xlsx文件
调整行和列
调整行高和列宽
import openpyxl
wb = openpyxl.Workbook()
sheet = wb.active
sheet['A1'] = 'Tall row'
sheet['B2'] = 'Wide column'
sheet.row_dimensions[1].height = 70
sheet.column_dimensions['B'].width = 20
wb.save('dimensions.xlsx')
合并和拆分单元格
import openpyxl
wb = openpyxl.Workbook()
sheet = wb.active
sheet.merge_cells('A1:D3') #合并单元格
sheet['A1'] = 'Twelve cells merged together'
sheet.merge_cells('C5:D5')
sheet['C5'] = 'Two merged cells.'
wb.save('merged.xlsx')
import openpyxl
wb = openpyxl.load_workbook('merged.xlsx') #拆分单元格
sheet = wb.active
sheet.unmerge_cells('A1:D3')
sheet.unmerge_cells('C5:D5')
wb.save('merged.xlsx')
冻结窗格
import openpyxl
wb = openpyxl.load_workbook('produceSales.xlsx')
sheet = wb.active
sheet.freeze_panes = 'C2'
# "A2" means freeze row1 'B1' means freeze columnA 'C2' means freeze row1 and columnA/columnB 'A1' or None means no freezed
wb.save('freezeExample.xlsx')
图表
import openpyxl
wb = openpyxl.Workbook()
sheet = wb.active
for i in range(1,11): #create some data in column A
sheet['A'+str(i)] = i
refObj = openpyxl.chart.Reference(sheet,min_row = 1,min_col = 1,max_row = 10,max_col = 1) #创建数据区域
seriesObj = openpyxl.chart.Series(refObj,title='First series')
chartObj = openpyxl.chart.BarChart()
chartObj.title = 'My chart'
chartObj.append(seriesObj)
sheet.add_chart(chartObj,'C5') #'C5'表示图表开始的位置
wb.save('sampleChart.xlsx')
习题与小结
- openpyxl.load_workbook()函数返回什么?
- 返回Workbook对象
- get_sheet_names()工作簿返回什么?
- 返回所有工作表名称构成的列表
- 如何取得名为“Sheet1”的工作表的Worksheet对象
- openpyxl.get_sheet_by_name("Sheet1")
- 如何取得工作不得活动工作表的Worksheet对象
- wb.get_active_sheet() / wb.active
- 如何取得单元格"C5"中的值
- sheet['C5'].value / sheet.cell(row=5,column=3).value
- 如何将单元格C5中的值设置成‘Hello’
- sheet['C5'] = 'Hello'
- 如何取得表示单元格的行和列的整数?
- get_column_letter(int) int --> char
- column_index_from_string char --> int
- max_row/max_column返回什么,返回值的类型是什么?
- sheet1.max_row 以整数方式返回单元格区域的行号
- sheet1.max_column 以整数方式返回单元格区域的列号
- 如果要取得列‘M’的下标,需要调用什么函数
- column_index_from_string('M')
- 如果要取得列14的字符串名称,需要调用什么函数
- get_column_letter(14)
- 如何取得从A1到F1的所有Cell对象的元组
- tuple(sheet['A1':'F1])
- 如何将工作簿保存到文件名example.xlsx?
- wb.save('example.xlsx')
- 如何在单元格中设置一个公式?
- sheet['B1'] = '==SUM(A1:B15)'
- 如果需要取得单元格中公式的结果,而不是公式本身,必须先做什么?
- 读取时使用data_only = True
- mannual打开和保存工作簿
- 如何将第5行的高度设置为100
- sheet.row_dimensions[5] = 100
- 如何将列C的宽度设置成70
- sheet.column_dimensions['C'] = 70
- 列出一些openpyxl2.1.4不会从xlsx中加载的功能
- 图表 #版本已更新,新版本未知
- 什么是冻结窗格?
- sheet.freeze_panes = 'C2' 冻结首行和A、B列
- 创建条形图的步骤和方法:
- 加载数据 openpyxl.load_workbook()
- 创建reference对象 #图表的数据源区域
- 创建series对象,并将reference对象加入到series对象中 #数据序列
- 创建chart对象,并将series对象加入到chart对象中(append方法)
- 将chart对象加入到sheet中(add_chart方法)
本文整理自 《python编程快速上手 让繁琐工作自动化》