python学习 21 excel分列

简单做了个模板,能干这个:

指定sheet中某列数据进行按需拆分,拆分后新建一个test的sheet,将数据分别存入test的不同列中。

python 复制代码
import os
import xlwings as  xw
import re
#excel路径
path=r'C:\Users\xxx\Desktop\123.xlsx'

#设置需要分列的sheet名
sheetname='Sheet1'
#设置需要分列的列名
colname='B'
#开始单元格
rowb=2
#结束单元格
rowe=25

def excel分列(path):
    excelapp=xw.App(visible=False, add_book=False)
    #打开excel
    excel = excelapp.books.open(path)
    #获取sheets
    sheet = excel.sheets
    #增加一个拆分用sheet,test
    if sheet[0].name !='test':
        sheet.add('test', before=sheet[0].name)
    #print(sheet[0].name)
    sheet2 = excel.sheets['Sheet1']

    #设置拆分条件,这里以复合字串为例,型如:你好123+好的234,拆成:你好,123,+,好的234
    num1=re.compile('\w.[0-9]')
    #print(re.findall(num1,sheet2.range('b2:b25').value[0])[0][:-1])
    num2=re.compile('\d++')
    #print(re.findall(num2,sheet2.range('b2:b25').value[0])[0])
    num3=sheet2.range('b2:b25').value[0].split('+')
    #print(num3[1])

    t1=[]
    t2=[]
    t3=[]
    t4=[]

    #拆分取值
    for i in sheet2.range(colname+str(rowb)+':'+colname+str(rowe)).value:
        t1.append(re.findall(num1,i)[0][:-1])
        t2.append(re.findall(num2,i)[0])
        t3.append('+')
        t4.append(i.split('+')[1])
    #print(t1,t2,t3,t4)
    #将拆分数据填入test中
    sheet3=excel.sheets['test']
    for i in range(len(t1)):
        sheet3.range('A'+str(i+1)).value=t1[i]
        sheet3.range('B' + str(i + 1)).value = t2[i]
        sheet3.range('C' + str(i + 1)).value = t3[i]
        sheet3.range('D' + str(i + 1)).value = t4[i]



    excel.save()
    excel.close()
    excelapp.quit()

excel分列(path)
相关推荐
小九九的爸爸9 小时前
前端想要入门Agent开发,要具备哪些Python基础?
python·agent·ai编程
阿耶同学10 小时前
手把手教你用 LangGraph 搭建三层嵌套 Agent 架构
python·程序员
花酒锄作田1 天前
Pydantic校验配置文件
python
hboot1 天前
AI工程师第四课 - 深度学习入门
pytorch·python·神经网络
ZhengEnCi2 天前
P2M-Matplotlib折线图完全指南-从数据可视化到趋势分析的Python绘图利器
python·matlab·数据可视化
ZhengEnCi2 天前
P2L-Matplotlib饼图完全指南-从数据可视化到图表定制的Python绘图利器
python·matlab
曲幽2 天前
你的REST接口还在“过度投喂”数据吗?——FastAPI + GraphQL实战避坑指南
python·fastapi·web·graphql·route·cors·rest·strawberry
用户8358086187912 天前
基于 Self-RAG 与列表级重排序的进阶 RAG 系统设计与实现
python
Warson_L2 天前
Python `Annotated` 与 LangGraph Reducer 学习笔记
python
韩师傅2 天前
海天线算法的前世今生
python·计算机视觉