首先要先下载openpyxl的包
在cmd中输入pip install openpyxl
等待下载完成
在PyCharm中设置
File=>Settings=>Project:项目目录=>python Interpreter
点击"+" 添加openpyxl
对excel的基本操作:
# coding:utf-8
# author:ChenBaijing
# date:2022/4/7 11:46
# 用python openpyxl 操作excel文档
from openpyxl import Workbook,load_workbook
from openpyxl.styles import Font,colors,Alignment
import datetime
# # --------创建--------
wb=Workbook() # 创建实例化
active_sheet=wb.active # 获取活跃的sheet页
active_sheet.title='pythonSheet' # 修改sheet名称
# 写入数据的几种方式
active_sheet['B9']='banana' # 直接按字典方式赋值
active_sheet['C9']='3.4元/斤'
active_sheet.append(['apple','2.8元/斤','万达广场','剩余60斤','水果区']) # 一次追加多个元素 会自动选择已有元素下面的行 从左开始
active_sheet['A3']=datetime.datetime.now().strftime('%y-%m-%d') # 类型会自动转换
wb.save('prac_excel_py.xlsx') # 保存操作
# # --------打开已有文件--------
wb2=load_workbook('prac_excel_py.xlsx')
sheet_list=wb2.sheetnames # 获取所有的sheet名称
print(sheet_list)
active_sheet=wb2[sheet_list[0]] # 指定操作的sheet wb2.['表单名称']
print(active_sheet['A10'].value) # 获取指定值
print('---------------------------------------------------------')
# 获取指定切片的数据 (min_col max_col 规定列) (min_row max_row 规定行)
for row in active_sheet.iter_rows(min_row=10,max_row=10):
for data in row:
print(data.value,end=' ')
print('\n---------------------------------------------------------')
# 获取sheet内的全部 按行遍历
print('****按行遍历****')
for row in active_sheet:
for cell in row:
print(cell.value,end=' ')
print()
print('****按列遍历****')
# 按列遍历
for column in active_sheet.columns:
for cell in column:
print(cell.value,end=' ')
print()
# # --------设置单元格样式--------
# 字体 对其方式 行高 列宽
wb3=load_workbook('prac_excel_py.xlsx')
active_sheet=wb3['pythonSheet']
# 字体
myfont=Font(name="宋体",size=10,italic=True,color=colors.BLUE)
active_sheet['C10'].font=myfont
# 对齐方式
alignm=Alignment(horizontal='center',vertical='center')
active_sheet['E10'].alignment=alignm
# 行高 列宽
active_sheet.row_dimensions[10].height=20
active_sheet.column_dimensions['A'].width=20
wb3.save('prac_excel_py.xlsx')