一、需要用到的模块
import openpyxl
import pandas
二、创建excel文件
wb = Workbook()
sheet = wb.active #获取当前active的sheet
print(sheet.title)
sheet.title = 'python小菜'
三、打开已有excel文件
from openpyxl import load_workbook
wb2 = load_workbook('excel_test.xlsx')
sheet = wb2.get_sheet_by_name("python小菜") #根据名字获取表格
#写入数据
sheet["B9"] = "小明" #一定要用双引号
sheet.append(["小兰",155,40]) #附加行,从第一列开始附加
四、保存,删除excel文件
wb.save('excel_test.xlsx')
#删除工作表
wb.remove(sheet)
del wb[sheet]
五、花式遍历excel
for cell in sheet["B5:B10"]: #获取指定列的切片数据
print(cell[0].value)
#按行循环遍历
for row in sheet:
print(row)
for cell in row:
print(cell.value,end=",")
print()
for row in sheet.iter_rows(min_row=4,max_row=21,max_col=5):
for cell in row:
print(cell.value,end=",")
print()
#按列循环,可以实现将excel的行变成列
for col in sheet.columns:
for cell in col:
print(cell.value,end=",")
print()
|