python openpyxl读取数据方法

读取excel 文档

#读取和关闭文档

import openpyxl

ws=openpyxl.load_workbook(excel_str_path)
sheet1=ws.sheetnames[0]

ws.close()

ws.save("文件名")  #保存到py文件当前目录,除非置顶路径。

写数据

# ⽅式⼀:数据可以直接分配到单元格中(可以输⼊公式)
sheet["C5"] = "Hello ⾦⻆⼤王"
sheet["C7"] = "Hello ⾦⻆⼤王2"
# ⽅式⼆:可以附加⾏,从第⼀列开始附加(从最下⽅空⽩处,最左开始)(可以输⼊多⾏)
sheet.append([1, 2, 3]) 
# ⽅式三:Python 类型会被⾃动转换
sheet['A3'] = datetime.datetime.now().strftime("%Y-%m-%d")

选择表

# sheet 名称可以作为 key 进⾏索引
ws3 = wb["New Title"]
ws4 = wb.get_sheet_by_name("New Title")
print(wb.get_sheet_names())  # 打印所有的sheet
sheet = wb.worksheets[0]  # 获得第1个sheet

遍历表数据

#按⾏遍历
for row in sheet:  # 循环获取表数据
    for cell in row:  # 循环获取每个单元格数据
        print(cell.value, end=",")
    print()

#按列遍历

# A1, A2, A3这样的顺序
for column in sheet.columns:
    for cell in column:
        print(cell.value,end=",")
    print()


#遍历指定⾏&列

# 从第2⾏开始⾄第5⾏,每⾏打印5列
for row in sheet.iter_rows(min_row=2,max_row=5,max_col=5):
    for cell in row:
        print(cell.value,end=",")
    print()


#遍历指定⼏列的数据-------取得第2-第5列的数据
for col in sheet.iter_cols(min_col=2,max_col=5,):
    for i in col:
        print(i.value,end=",")
    print()


#表对象[位置1:位置2] - 获取指定范围中的所有的单元格
#sheet['A1':'A%d' %max]    正确方式
#s1=sheet['B2':f'C{max_row}']    错误方式


max_column = sheet.max_column       # 获取最大列数
column = get_column_letter(max_column)      # 获取最大列数对应的字母列号
# 获取第一行所有单元格对象
row2 = sheet['A1':'%s1' % column]    # ((<Cell '表1'.A1>, <Cell '表1'.B1>, <Cell '表1'.C1>),)
 
for row_cells in row2:
    for cell in row_cells:
        print(cell.coordinate, cell.value)




# 获取整个列的单元格  整列单元格数据也要读取单独行  column_cells[0].value
max_row = sheet.max_row
columnB = sheet['A1':'A%d' % max_row]
# 获取B列对应的所有单元格对象
for column_cells in columnB:
    for cell in column_cells:
        print(cell.coordinate, cell.value)



# 获取矩形区域中的单元格对象   
cell_tuples = sheet['A1': 'C3']
for cells in cell_tuples:
    for cell in cells:
        print(cell.coordinate, cell.value)

#使用行+列索引  row[1]  行中的第一列
for row in  sheet.iter_rows(min_row=2,max_row=sheet.max_row,max_col=sheet.max_column):
    name1=row[1].value
    time1=str(row[4].value)
    bh1=str(row[2].value)+"--"+str(row[3].value)

#使用lie+列索引  row[1]  行中的第一列


把数据转化成list或字典


for row in  sheet.iter_rows(min_row=2,max_row=sheet.max_row,max_col=sheet.max_column):
    studen_info_dic[row[1].value]=list(i.value for i in row)

 

  • 3
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值