使用pip安装openpyxl。pip为python3.7中自带的,路径为E:\python\Scripts。通过cmd安装。
有时候安装库比较慢,可以使用国内的镜像安装:(如安装opencv)
用阿里云:
pip install -i https://mirrors.aliyun.com/pypi/simple opencv-python
用清华大学:
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple opencv-python
'''
openpyxl的安装使用pip安装。
在第一次运行程序时报错,显示没有找到load_workbook模块,排查后原因为:该程序文件名
是openpyxl.py,与模块名称相同,python懵了,改名即可运行
'''
import openpyxl
help(openpyxl)#多使用help
from openpyxl.utils import get_column_letter,column_index_from_string
help(openpyxl.utils.get_column_letter) #Convert a column index into a column letter,3 -> 'C'
help(openpyxl.utils.column_index_from_string)#Convert a column name into a numerical index,('A' -> 1)
#open the workbook
wb=openpyxl.load_workbook('students.xlsx') #此时程序文件与excel文件必须在同一路径下
'''
在idle中,openpyxl. 后面的函数不会自动弹出,但是wb. 后面的函数会自动弹出
'''
#getting sheets from the workbook
print(wb.sheetnames) #输出['Sheet1'],默认为3个表单但是该文件只有sheet被填写
for s in wb:
print(s.title) #遍历sheet与上一句相同,输出Sheet1
#creat a worksheet
Newsheet=wb.create_sheet('newsheet')
print(wb.sheetnames) #输出 Sheet1,newsheet
'''
sheet3=wb.get_sheet_by_name('newsheet') #获得某张表单
sheet4=wb['sheet1'] ##获得某张表单
'''
#getting cell from sheet
ws=wb.active #指正在活跃的表单,默认为第一张
#ws为Worksheet
'''
ws. 后面的函数也会自动弹出
'''
print(ws) #<Worksheet "Sheet1">
print(ws['A1']) #<Cell 'Sheet1'.A1>
print(ws['A1'].value) #输出表单A1单元格的值,“学号”
x=ws['B1']
print('ROW{},COLUNM{} IS {}'.format(x.row,x.column,x.value)) #ROW1,COLUNM2 IS 姓名
print('Cell {} is {}'.format(x.coordinate,x.value)) #coordinate可以输出坐标。输出Cell B1 is 姓名
print(ws.cell(row=1,column=2)) #<Cell 'Sheet1'.B1>。与前面的ws['A1']一样,但是这种方法可以使用for循环
print(ws.cell(row=1,column=2).value) #姓名
for i in range(1,3): #只能从1开始,excel没有第0行
print(ws.cell(row=i,column=2).value)
#getting rows and columns from the sheets
column1=ws['A']
print(column1) #(<Cell 'Sheet1'.A1>, <Cell 'Sheet1'.A2>, <Cell 'Sheet1'.A3>, <Cell 'Sheet1'.A4>)
print(column1[2].value) #输出为A列第3行的内容,因为column是从[0]开始
row3=ws[3] #第三行
col_range=ws['A:C'] #范围切片
row_range=ws[1:3]
for col in col_range:
for cell in col:
print(cell.value)
'''
学号
1
2
3
姓名
张晗
tom
tony
成绩
95
85
75
'''
#===============================================
cell_ran = ws['A1:D3']
for row_cell in cell_ran: #先行
for cellbj in row_cell: #行中取单元格
print(cellbj.coordinate,cellbj.value)
print('----end of the row----------')
'''
A1 学号
B1 姓名
C1 成绩
D1 None
----end of the row----------
A2 1
B2 张晗
C2 95
D2 None
----end of the row----------
A3 2
B3 tom
C3 85
D3 None
----end of the row----------
'''
#==========输出行列的个数============
print('行:{} 列:{}'.format(ws.max_row,ws.max_column)) #行:4 列:4
print(get_column_letter(2),get_column_letter(85)) #输出:B CG 。即第2列代号为B,第85列为CG