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)
相关推荐
nightunderblackcat23 分钟前
进阶向:人物关系三元组,解锁人物关系网络的钥匙
开发语言·python·开源·php
站大爷IP39 分钟前
Pandas与NumPy:Python数据处理的双剑合璧
python
站大爷IP1 小时前
Python枚举进化论:IntEnum与StrEnum的实战指南
python
甄超锋1 小时前
python sqlite3模块
jvm·数据库·python·测试工具·django·sqlite·flask
long3162 小时前
构建者设计模式 Builder
java·后端·学习·设计模式
R-G-B2 小时前
OpenCV Python——Numpy基本操作(Numpy 矩阵操作、Numpy 矩阵的检索与赋值、Numpy 操作ROI)
python·opencv·numpy·numpy基本操作·numpy 矩阵操作·numpy 矩阵的检索与赋值·numpy 操作roi
细节处有神明2 小时前
Jupyter 中实现交互式图表:ipywidgets 从入门到部署
ide·python·jupyter
小小码农一只2 小时前
Python 爬虫实战:玩转 Playwright 跨浏览器自动化(Chromium/Firefox/WebKit 全支持)
爬虫·python·自动化
深盾安全4 小时前
Python脚本安全防护策略全解析(上)
python
杜子不疼.4 小时前
《Python学习之使用标准库:从入门到实战》
开发语言·python·学习