python中的xlwings操作excel工作表学习笔记

import xlwings as xw
from subprocess import PIPE, Popen

def kill_process(process_name):
# 构建命令
command = f’taskkill /f /im {process_name}’

# 启动进程
proc = Popen(
    command,
    stdin=None,
    stdout=PIPE,
    stderr=PIPE,
    shell=True)

# 与进程交互
outinfo, errinfo = proc.communicate()

# 处理输出
if proc.returncode != 0:
    # 输出错误信息
    err_info = errinfo.decode('gbk')
    err_info_cn = '\n'.join(line for line in err_info.splitlines() if line.strip())
    print(err_info_cn)
else:
    # 输出成功信息
    out_info = outinfo.decode('gbk')
    out_info_cn = '\n'.join(line for line in out_info.splitlines() if line.strip())
    print(out_info_cn)

def create_excel_app(visible=False, add_book=False):

# 创建 Excel 应用程序对象
app = xw.App(visible=visible, add_book=add_book)

# 配置应用程序对象
app.visible = visible  # 设置可见性
app.display_alerts = False  # 关闭警告
app.screen_updating = False  # 关闭屏幕更新

# 返回应用程序对象
return app

#======================================================
def operate_worksheets_in_workbook(app,workbook_name):
wb = app.books.open(workbook_name) # 打开指定的工作簿
sheets = wb.sheets # 获取工作簿中的所有工作表

# 循环遍历所有工作表,跳过第一个和最后一个
print("=======01.工作簿中对工作表的操作展示============")
print(">>>对工作表遍历,不处理最后1个和第1工作表!!!")
for index, sheet in enumerate(sheets):
    if wb.sheets[index].api.AutoFilterMode:
        print(f"工作表{sheet.name}已经存在筛选")
    else:
        print(f"工作表{sheet.name}没有筛选")
    # 跳过第一个和最后一个工作表
    if index == 0 or index == len(sheets) - 1:
        continue
    # 在这里执行你想要做的操作
    print(sheet.name)
 #sht = wb.sheets[0]                #引用工作表方式1
sht = wb.sheets("sheet1")      #引用工作表方式2
data =  sht.range('A1').expand().value  # 读取整个工作表的值
for row in data:  # 遍历读取到的值并考虑None
    for cell in row:
        if cell is not None:
            print(cell, "\t", end="")
        else:
            print("None", "\t", end="")
    print("")    

wb.close()

def operate_workbook_in_cells(app,workbook_name):
wb = app.books.open(workbook_name) # 打开指定的工作簿
print(“=02.工作中单元操作展示======”)
# msg_info = “你好,我是一个对话框”
# app.alert(msg_info, title=“标题”, buttons=“ok”, mode=“info”)

对行高列宽进行调整

wb.sheets['Sheet1'].autofit('c')  # 自动调整列宽(引用工作表方式3)
wb.sheets['Sheet1'].autofit('r')  # 自动调整行高
wb.sheets['Sheet1'].autofit()  # 同时调整

sht = wb.sheets[0]
# 单元格值的读写
cell_value = sht["a1"].value
print(cell_value)
sht["D6"].value = "wahaha"  # 写入

read_table_value = sht.range("A1:D4").value  # 读取列表值到一个二维列表里
print(read_table_value)

# 默认情况下,带有数字的单元格读取为float,但您可以将其更改为int:
ret_int = sht['C2'].options(numbers=int).value
print(f"读取数字类型{ret_int}")
print(sht['C2'].value)  # 这个默认读取成浮点数
print(f"============工作表列表:{wb.sheet_names}")

data = sht.range('A1').expand().value  # 读取整个工作表的数据方式1
table_value = sht.used_range.value  # 读取整个工作表的数据方式2
print(table_value)

wb.save()
wb.close()

if name == “main”:
kill_process(“et.exe”) # 调用函数终止 et.exe 进程
app = create_excel_app() # 创建app对象
BookNameFile = r"test.xlsx"
operate_worksheets_in_workbook(app, BookNameFile) # 打开工作簿循环遍历每个工作表进行操作
operate_workbook_in_cells(app,BookNameFile) # 对工作表中的单元格和单元格区域进行操作
app.kill()

  • 5
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值