pywin32/wincom32设置excel格式

这段代码使用Python的win32com库与Excel交互,实现对Excel文件中特定列的格式修改。它首先打开文件,然后设置列的数字格式,并执行文本到列的转换。在第二段代码中,它扩展了功能,可以同时处理多列的不同格式定义。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、修改一列格式

import win32com.client as client
from win32com.client import constants


xl_app = client.gencache.EnsureDispatch("Excel.Application")
xl_app.Visable = False
fileName = ""
sheetName = ""
f = xl_app.Workbooks.Open(fileName)
sht = f.WorkbooksOpen(sheetName)
sht.Range("A:A").NumberFormatLocal = "0.00_ "
sht.Columns("A:A").TextToColumns(Destination=sht.Range("A1"), DataType=1, TextQualifier=1, ConsecutiveDelimiter=False, Tab=True, Semicolon=False, Comma=False, Space=False, Other=False, FieldInfo=(1, 1), TrailingMinusNumbers=True)
f.Save()
f.Close()
xl_app.Quit()

2、修改多列格式

import win32com.client as client
from win32com.client import constants


xl_app = client.gencache.EnsureDispatch("Excel.Application")
xl_app.Visable = False
fileName = ""
sheetName = ""
f = xl_app.Workbooks.Open(fileName)
sht = f.WorkbooksOpen(sheetName)
formatDefine = ["0.00_ ", "####-##-##"]
rangeDefine = ["A:A", "D:D"]
firstCell = ["A1", "D1"]
for x, y, z in zip(formatDefine, rangeDefine, firstCell):
    sht.Range(y).NumberFormatLocal = x
    sht.Columns(y).TextToColumns(Destination=sht.Range(z), DataType=1, TextQualifier=1, ConsecutiveDelimiter=False, Tab=True, Semicolon=False, Comma=False, Space=False, Other=False, FieldInfo=(1, 1), TrailingMinusNumbers=True)
f.Save()
f.Close()
xl_app.Quit()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值