【python办公自动化 | Datawhale】Task02 Python与Excel

"""
练习1
将用户行为偏好.xlsx中sheet1表中空着向前填充
"""
import openpyxl
#注:只能读取xlsx格式
import os
os.chdir(r'C:\Users\huangyan\Desktop\OfficeAutomation')#设置路径
os.getcwd()#检验
wb=openpyxl.load_workbook('用户行为偏好.xlsx')#导入数据
print(wb.sheetnames)#打印sheet
sheet = wb.get_sheet_by_name('订单时长分布')#指定sheet
max_col=sheet.max_column#计算表格最大列数
max_row=sheet.max_row#计算表格最大行数
for row in sheet.iter_rows(min_row=2,max_row=max_row,
                           min_col=1,max_col=max_col):
    for cell in row:
        if not str(cell.value).strip():#去掉空格再判断
            cell.value=sheet.cell(cell.row-1,cell.col_idx).value
            print(cell.coordinate+' = '+str(cell.value))
            #print(cell.coordinate)
wb.save('new_wb.xlsx')
"""
练习2
打开test文件,找出文件中人流量超过150000的行,并对其标红、加粗、附上边框。
"""
test=openpyxl.load_workbook('test.xlsx')#导入excel
print(test.sheetnames)#打印sheet
sheet=test.get_sheet_by_name('work')#指定sheet
max_col=sheet.max_column#计算表格最大列数
max_row=sheet.max_row#计算表格最大行数
from openpyxl.styles import  Font, Side, Border
font = Font(bold=True,  color='FF0000')#设置字体
side = Side(style='thin', color='FF000000')#设置线形
border = Border(left=side, right=side, top=side, bottom=side)#设置边框
for i in range(2,max_row + 1):
    if int(sheet.cell(i,2).value)>=150000:
        sheet.cell(i,2).font=font
        sheet.cell(i,2).border=border
test.save('new_test.xlsx') #保存到新文件

说明:代码主要来自Datawhale的学习文档

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值