准备一个excel文件,这里是:e\t.xlsx,放文件里随便写几条数据。
注意:扩展名必须是xlsx(excel 2007及以上版本的),因为openpyxl模块只能处理xlsx文件。
一、安装openpyxl模块
C:\Users\Administrator>pip install openpyxl
Collecting openpyxl
Downloading openpyxl-2.4.1.tar.gz (154kB)
39% |████████████▊ | 61kB 184kB/s eta 0:00:01
46% |██████████████▉ | 71kB 196kB/s eta 0:00:
52% |█████████████████ | 81kB 215kB/s eta 0:0
59% |███████████████████ | 92kB 233kB/s eta 0
66% |█████████████████████▏ | 102kB 247kB/s e
72% |███████████████████████▎ | 112kB 335kB/s
79% |█████████████████████████▍ | 122kB 395kB
86% |███████████████████████████▌ | 133kB 423
92% |█████████████████████████████▊ | 143kB 5
99% |███████████████████████████████▉| 153kB
100% |████████████████████████████████| 163k
B 528kB/s
Collecting jdcal (from openpyxl)
Downloading jdcal-1.3.tar.gz
Collecting et-xmlfile (from openpyxl)
Downloading et_xmlfile-1.0.1.tar.gz
Installing collected packages: jdcal, et-xmlfile, openpyxl
Running setup.py install for jdcal ... done
Running setup.py install for et-xmlfile ... done
Running setup.py install for openpyxl ... done
Successfully installed et-xmlfile-1.0.1 jdcal-1.3 openpyxl-2.4.1
You are using pip version 8.1.1, however version 9.0.1 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' comm
and.
二、基本用法
# -*- coding:gbk -*-
import openpyxl
workbook= openpyxl.load_workbook('e:\\t.xlsx')
print(type(workbook))
#工作簿中所有的 sheet
print(workbook.get_sheet_names())
#返回sales表格
sheet=workbook.get_sheet_by_name('sales')
print(sheet,type(sheet))
#打印sheet的标题
print('\nsheet标题:'+sheet.title)
#返回当前的表格
sheet2=workbook.get_active_sheet()
print('\n当前sheet标题:'+sheet2.title)
#这2个函数已经不能用了
#print('sheet总行数:'+str(sheet.get_highest_row()))
#print('sheet总列数:'+str(sheet.get_highest_column()))
##已无效,适用于旧版本
##for row in sheet.columns[1]:
## print(row.value)
#sheet的行数、列数,现在不用函数,直接用属性
#openpyxl.__version__ 版本号是 '2.4.1'
print('\nsheet行范围:'+str(sheet.max_row)+'~'+str(sheet.max_row))
print('sheet列范围:'+str(sheet.min_column)+'~'+str(sheet.max_column))
#1.直接指定单元格取数据
r = sheet['A1']
print('\n['+str(r.coordinate)+'] '+ str(r.column) +':'+ str(r.row) + ' =' + r.value)
print('['+str(sheet['A1'].coordinate)+'] '+ str(sheet['A1'].column) +':'+ str(sheet['A1'].row) + ' =' + sheet['A1'].value)
#2.通过行、列号取数据
c=sheet.cell(row=1,column=1)
print('['+str(c.coordinate)+'] '+ str(c.column) +':'+ str(c.row) + ' =' + c.value)
#单元格数据
for row in sheet['a1':'a3']:
for col in row:
print(col.value)