使用工具
编译器:Pycharm
python版本:3.7
主要使用的第三方库:openpyxl
数据读取
import openpyxl
from openpyxl.utils import get_column_letter,column_index_from_string # excel 中的序号 数字变字母 字母变数字
wb = openpyxl.load_workbook('data.xlsx') # 打开已存在的文件data.xlsx
print(wb.sheetnames) # 打印所有的表名 ['Sheet1', 'Sheet2', 'Sheet3']
for sheet in wb: # 在wb中的所有sheet
print(sheet.title) # 用循环语句遍历各表名
mysheet = wb.create_sheet('mysheet') # 创建新表名
print(wb.sheetnames) # ['Sheet1', 'Sheet2', 'Sheet3', 'mysheet']
ws = wb.active
print(ws) # <Worksheet "Sheet1">
1.从工作表中获取单元格信息
# Getting cells from the sheets
print(ws['A1'].value) # 取值记得用value函数 打印'A1'单元格中的数值 name
c = ws['B1']
print('Cell {} is {}'.format(c.coordinate, c.value)) # coordinate函数标记cell的位置 row 1,col 2 is number
print('row {},col {} is {}'.format(c.row, c.column, c.value)) # row 1,col 2 is number format将()的数值赋给前面大括号的内容
print(ws.cell(row=1, column=3).value) # price 注意Excel中索引从1开始,不是从零开始 打印一行三列的数据
for i in range(1, 10, 2): # 取值范围1-10,步长为2
print(i, i+1, ws.cell(row=i, column=i+1).value) # 打印i行i+1列的值,i每次加2 range函数中的三个值分别是索引起始位置,终止位置以及步长
2.从工作表中获取行、列信息
# Getting cells from the sheets
print(ws['A1'].value) # 取值记得用value函数 打印'A1'单元格中的数值 name
c = ws['B1']
print('Cell {} is {}'.format(c.coordinate, c.value)) # coordinate函数标记cell的位置 row 1,col 2 is number
print('row {},col {} is {}'.format(c.row, c.column, c.value)) # row 1,col 2 is number format将()的数值赋给前面大括号的内容
print(ws.cell(row=1, column=3).value) # price 注意Excel中索引从1开始,不是从零开始 打印一行三列的数据
for i in range(1, 10, 2): # range函数中的三个值分别是索引起始位置,终止位置以及步长
print(i, i+1, ws.cell(row=i, column=i+1).value)
# Getting rows and cols from the sheets
colC = ws['B']
# print(colC[2].value) # 取得B列第二行中的数句,因为索引从0开始,行标从一开始
row6 = ws[4]
# print(row4[1].value) # 第4行第二列的数据
col_range = ws['A:B']
row_range = ws['1:7'] # 用range函数控制打印的单元格范围'''
for col in col_range: # 按列输出每一列
for cell in col:
print(cell.value)
for row in row_range: # 按行输出每一行
for cell in row:
print(cell.value)
for row in ws.iter_rows(min_row=1, max_row=7, max_col=2): # ****
for cell in row:
print(cell.value)
# print(tuple(ws.rows))
cell_range = ws['A1:B7']
for row0cell0objects in cell_range:
for cell0 in row0cell0objects:
print(cell0.coordinate, cell0.value) # 打印A1-B7的数据并标明每一个数据的位置 ****注意coordinate 函数
print('-----')
print('{}*{}'.format(ws.max_row, ws.max_column)) # 输出excel是*x*矩阵
print(get_column_letter(78)) # 获取第78列在excel中的列序 数字变字母
print(column_index_from_string('BZ')) # excel中的序号 字母变数字
代码如上,以下为相关数据截图
结语:以上为有关python联动excel进行数据读写的入门教程内容,才疏学浅,如有谬误,还请各位批评指正,也欢迎大家对本文或是本人提出相关合理的建议,希望能和诸位接下来的日子里相互学习,共同进步。