openpyxl模块读取excel文件

from openpyxl import load_workbook
filepath = r"C:\Users\fengzi\Desktop\机型维表.xlsx"

wb = load_workbook(filepath)
sheet = wb["Sheet1"]        
maxrow = sheet.max_row          #获取最大行
minrow = sheet.min_row          #获取最小行
maxcolumn = sheet.max_column    #获取最大列
mincolumn = sheet.min_column    #获取最小列


#按行读取文件
for row in range(minrow, maxrow):
    for column in range(mincolumn, maxcolumn):
        print(sheet.cell(row, column).value, end=" ")
    print()

结果为

 

按行写入excel

 

from openpyxl import load_workbook
from openpyxl import workbook
filepath = r"C:\Users\fengzi\Desktop\机型维表.xlsx"

wb = load_workbook(filepath)
sheet = wb["Sheet1"]
maxrow = sheet.max_row          #获取最大行
minrow = sheet.min_row          #获取最小行
maxcolumn = sheet.max_column    #获取最大列
mincolumn = sheet.min_column    #获取最小列


list2 = []
#按行读取文件
for row in range(minrow, maxrow):
    list1 = []
    for column in range(mincolumn, maxcolumn):
        list1.append(sheet.cell(row, column).value)
    list2.append(list1)
print(list2)
wb = workbook.Workbook()
for line in list2:
    sheet = wb.active
    sheet.append(line)
wb.save(r"C:\Users\fengzi\Desktop\机型维表2.xlsx")

 

最后结果为

 

posted @ 2021-11-26 10:41  力王7314  阅读(119)  评论(0编辑  收藏  举报