Python 办公自动化-Excel写入
创建并保存Excel文件
import openpyxl
workbook=openpyxl.Workbook() #创建空Excel文件
sheet=workbook.active #获取活动的工作表
sheet.title=“测试“ #修改sheet工作表名称为测试
workbook.save(“data\input\Test.xlsx”) #保存Excel文件
创建&删除工作表
#创建工作表sheet,默认为sheet1,sheet2…依次递增
workbook.create_sheet()
#通过关键字参数,指定工作表索引,创建工作表
workbook.create_sheet(index=0,title="测试1")
#删除指定的工作表
del workbook["Sheet"]
workbook.remove(workbook["测试"])
写入某个单元格
import openpyxl
workbook=openpyxl.Workbook()
sheet=workbook.active
sheet[“A1”]=“产品名称” #产品名称写入A1单元格
sheet[“A2”]=“华为手机” #华为手机写入A2单元格
workbook.save("data\input\Test.xlsx")
批量向单元格写入数据
import openpyxl
workbook=openpyxl.Workbook()
sheet=workbook.active
data_list=[
["产品编号","产品名称","零售价格","销售数量"],
["A1001", "PG手机", "4500", "18"],
["A1002", "HW电脑", "7500", "5"],
["A1003", "HW平板", "2300", "10"],
["B1001", "HW手机", "5500", "12"],
["B1001", "HW手机", "5500", "12"]
]
for row in data_list:
sheet.append(row)
workbook.save("data\input\Test.xlsx")
读取A Excel文件筛选后写入B Excel文件
from openpyxl import load_workbook
from openpyxl import Workbook
def filter_excel(source_file, target_file):
# 打开源文件和目标文件
source_wb = load_workbook(source_file)
target_wb = Workbook()
# 获取源文件和目标文件的工作表
source_sheet = source_wb.active
target_sheet = target_wb.active
#写入标题列
title_row = list(source_sheet.iter_rows(min_row=1, max_row=1,max_col=4, values_only=True))[0]
target_sheet.append(title_row)
# 遍历源文件的每一行
for row in source_sheet.iter_rows(min_row=2,max_row=29,min_col=1,max_col=4):
# 获取价格所在的列索引
price = row[2].value
# 检查价格是否大于5000
if price and price > 5000:
# 将符合条件的行写入目标文件,遍历每行的单元格的值,以列表形式返回
target_sheet.append([cell.value for cell in row])
# 保存目标文件
target_wb.save(target_file)
# 调用函数
filter_excel("data\input\销售明细表.xlsx", "data\input\Test.xlsx")
效果如下