使用openpyxl读取excel

时间:2019-11-06
本文章向大家介绍使用openpyxl读取excel,主要包括使用openpyxl读取excel使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

读取excel

import openpyxl
workbook = openpyxl.load_workbook("test.xlsx")
#通过文件名得到文件对象
sheet_name = workbook.get_sheet_by_name("Sheet1")
#通过名称得到工作簿对象
# rows_sheet = sheet_name.rows
#按行生成工作表中所有单元格对象,生成器类型
rows = [item.value for item in list(sheet_name.rows)[1]]
print(rows)
#第二行的内容
cols = [item.value for item in list(sheet_name.columns)[1]]
print(cols)
#第二列的内容
rows_sheet = sheet_name.iter_rows()
for item in rows_sheet:
    for call in item:
        print(call.coordinate, call.value)
#遍历所有内容
cell_1_2 = sheet_name.cell(row=1,column = 2).value
print(cell_1_2)
#查看第一行第二列的单元格内容
print(sheet_name.max_row,sheet_name.max_column)
#最大行、列

 写入excel

import openpyxl

workbook = openpyxl.Workbook()

sheet = workbook.active
'''
sheet['B3'] = "hi,wwu"

workbook.save('new.xlsx')
#通过excel坐标直接写入对应的单元格
'''


title_excel = ['username','password','age','sex']

for i in range(len(title_excel)):
    sheet.cell(row = 1, column = i+1).value = title_excel[i]
#通过行、列写入
workbook.save('new.xlsx')

原文地址:https://www.cnblogs.com/wbw-test/p/11778474.html