告别重复工作,Python 操作 xlwings 实例演示!

85bb778542370902bd348cf2db48c5b8.gif

作者 | 派森酱

来源 | Python技术

阿里云产品费用巡检,一般流程是登录账号,再逐项核对填写。虽然简单,但如果帐号多表格多,帐号间的数据有关联,填写起来就比较费力气。几张表格,可能从下载数据到核写完毕,辗转半个小时。

因此在保留excel原文件格式不变的基础上,自动填写相关数值变得重要。

python操作excel的模块多,xlrd,pandas,xlwings,openpyxl。经常搞不清这么多功能类似的模块有什么区别,这里发现xlwings可以派上用场,因为我有个保留excel格式的需求,文件格式:

表1-1182b38c8e77643108931b9516c81055b.png

注意:主要修改第10、11行,其它不变。

数据来源

通过爬虫登录阿里云,下载数据写入csv。带上日期,如data_07-25.csv

表1-2

dad3fd87c409d0fcde2815d4621489a4.png

爬虫脚本

# -*- coding: utf-8 -*-
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import time,os,glob,csv
from datetime import datetime

options = Options()
options.add_argument('--disable-infobars')
options.add_argument('--incognito')
# options.add_argument('--headless')
bro = webdriver.Chrome(executable_path='C:\drf2\drf2\chromedriver.exe', chrome_options=options)
bro.maximize_window()
bro.get('https://www.aliyun.com/')
bro.implicitly_wait(10)

#点击首页的登录按钮
bro.find_element_by_xpath('//*[@id="J_3207526240"]/div/div/div[1]/div[2]/div[2]/a[4]').click()
time.sleep(1)
#点击RAM用户
bro.find_element_by_xpath('//*[@id="root"]/div/div[2]/div/div[2]/div[1]/div[2]/div[2]/div/div[2]/div[2]/span/div').click()

u = bro.find_element_by_xpath('//*[@id="--aliyun-xconsole-app"]/div[1]/div[2]/div/div/div[1]/div[2]/div/div/div[2]/div/div/div/form/div[1]/div[2]/div[1]/span/input')
#用户名
u.send_keys('')
time.sleep(5)
#点击下一步
bro.find_element_by_xpath('//*[@id="--aliyun-xconsole-app"]/div[1]/div[2]/div/div/div[1]/div[2]/div/div/div[2]/div/div/div/form/div[5]/button/span').click()
p = bro.find_element_by_xpath('//*[@id="--aliyun-xconsole-app"]/div[1]/div[2]/div/div/div[1]/div[2]/div/div/div[2]/div/div/div/form/div[2]/div[2]/span/input')
#密码
p.send_keys('')
time.sleep(5)
# 点击登录按钮
bro.find_element_by_xpath('//*[@id="--aliyun-xconsole-app"]/div[1]/div[2]/div/div/div[1]/div[2]/div/div/div[2]/div/div/div/form/div[5]/button/span').click()
time.sleep(3)
# 点击控制台
bro.find_element_by_xpath(
    '//*[@id="J_3207526240"]/div/div/div[1]/div[2]/div[2]/a[3]').click()
time.sleep(6)
#切换窗口
bro.switch_to.window(bro.window_handles[-1])
# 点击费用
bro.find_element_by_xpath(
    '/html/body/div[1]/div/div/nav/div[1]/a').click()
time.sleep(3)
bro.switch_to.window(bro.window_handles[-1])
available_credit = bro.find_element_by_xpath('//*[@id="app__home"]/div/div/div/div[2]/div[1]/div[1]/div[2]/div/div[1]/span[1]/span').text
time.sleep(3)
#点击帐单详情
bro.find_element_by_xpath(
    '//*[@id="root-app"]/div[1]/div/div[6]/div[3]/a').click()
time.sleep(1.5)
#点击产品量价汇总
bro.find_element_by_xpath(
    '//*[@id="app__ent-expense"]/div/div/div[1]/div[1]/div/div/div/ul/li[4]/div/span').click()
time.sleep(1.5)

trs = bro.find_elements_by_xpath('//tbody/tr[position()> 1]')

for f in os.listdir('C:/Users/Administrator/Desktop/费用巡检/'):
    if f.startswith('fee'):
        os.remove('C:/Users/Administrator/Desktop/费用巡检/%s' % f)
with open('C:/Users/Administrator/Desktop/费用巡检/fee_%s.csv' % datetime.now().__format__('%m-%d'), 'a+', newline='', encoding='gb18030') as f:
    f_csv = csv.writer(f)
    f_csv.writerow(['可用额度',available_credit.split(' ')[1]])
    for tr in trs:
        tr = tr.text.split('\n')
        f_csv.writerow([tr[0],tr[1].split(' ')[1]])

bro.quit()

上手

pandas读取表1-2的数据

为了方便识别,变量名直接用中文了

import pandas as pd

df = pd.read_csv('data_%s.csv' % datetime.now().__format__('%m-%d'), encoding='gbk', names=['内容', '金额'])
内容安全 = eval(df.iloc[5, 1])
系统短信 = 0
云服务器ECS流量 = eval(df.iloc[4, 1])
对象存储 = eval(df.iloc[8, 1])
文件存储 = eval(df.iloc[6, 1])
视频点播 = eval(df.iloc[11, 1])
大数据 = eval(df.iloc[2, 1]) + eval(df.iloc[7, 1])
CDN = eval(df.iloc[1, 1])
日志服务 = eval(df.iloc[10, 1])
块存储 = eval(df.iloc[3, 1])
合计 = round(内容安全 + 系统短信 + 云服务器ECS流量 + 对象存储 + 文件存储 + 视频点播 + 大数据 + CDN + 日志服务 + 块存储, 2)
余额 = eval(df.iloc[0, 1].replace(',', ''))

xlwings获取表1-1sheet

import xlwings as xw
from datetime import datetime
import os

app = xw.App(visible=False,add_book=False)
app.display_alerts = False
app.screen_updating = False

wb = app.books.open(filename)
ws = wb.sheets[0]

xlwings修改表1-1数据

# 修改第10行,expand参数可以方便的按顺序一行写完
ws.range('B10').options(expand='table').value = [内容安全, 系统短信, 云服务器ECS流量, 对象存储, 文件存储, 视频点播, 大数据, CDN, 日志服务, 块存储, 合计,
                                                    余额]

# 修改第11行
ws.range('e41').value = '本月(%s月)已使用%s元,实际账户余额为%s元。' % (datetime.now().month, 合计, 余额)
path = 'D:/桌面/巡检/%s' % datetime.now().__format__('%m-%d')
if not os.path.exists(path):
    os.mkdir(path)
wb.save(os.path.join(path,'教育费用_%s.xlsx' % datetime.now().__format__('%m-%d')))
wb.close()
app.quit()

总结

通过使用xlwings自动修改表格,我的6张表格从原先的操作半小时,到现在鼠标duang~duang~duang~几下即可做好。减少上百次的复制粘贴点击后,工作更轻松了。

 
  

5ca66ef8942a4183e36405217cb3f43c.gif

往期回顾

“如今,99%以上的代码都是垃圾!”

Deepfake 技术换脸真假难辨!

撒贝宁搭档数字人主持,还是头一回!

7岁男童因下棋太快,被机器人夹断手指?

分享
点收藏
点点赞
点在看

猜你喜欢

转载自blog.csdn.net/dQCFKyQDXYm3F8rB0/article/details/126025704