Python3 去除 Excel 空白
admin
2023-05-20 20:22:47
0

【环境】

    Windows 10 下,Python 3.6,使用第三方包 openpyxl。


【config.ini】

[config]
; Excel 文件名
XlFile=D:\test\test.xlsx
; 需处理的表单名
SheetName=Sheet1


【trim_cell_for_excel.py】

# encoding: utf-8
# author: walker
# date: 2018-09-26
# summary: 去除 Excel 单元格内字符串前后的空白

import os
import sys
import time
import openpyxl
from configparser import ConfigParser

StartTime = time.time()
cur_dir_fullpath = os.path.dirname(os.path.abspath(__file__))

XlFile = r''
SheetName = r''

def ReadConfig(): 
    r""" 读取配置文件 """
    global XlFile, SheetName
    
    cfg = ConfigParser()
    cfgFile = os.path.join(cur_dir_fullpath, r'config.ini')
    if not os.path.exists(cfgFile):
        input(cfgFile + ' not found')
        sys.exit(-1)
    with open(cfgFile, mode='rb') as f:
        content = f.read()
    if content.startswith(b'\xef\xbb\xbf'):     # 去掉 utf8 bom 头
        content = content[3:]
    cfg.read_string(content.decode('utf8'))
    if not cfg.sections():
        input('Read config.ini failed...')
        sys.exit(-1)
        
    XlFile = cfg.get('config', 'XlFile').strip()          
    if not os.path.exists(XlFile):
        print('Error: not exists %s' % XlFile)
        sys.exit(-1)
    print('XlFile: %s' % XlFile)
    
    SheetName = cfg.get('config', 'SheetName').strip() 
    print('SheetName: %s' % SheetName)
        
    print('Read config.ini successed!')

def Main():
    print('Load %s ...' % XlFile)
    wb = openpyxl.load_workbook(XlFile)
    print('Load %s success!' % XlFile)
    sheet = wb[SheetName]
    for i in range(1, sheet.max_row + 1):
        for j in range(1, sheet.max_column + 1):
            rawVal = sheet.cell(i, j).value
            if not isinstance(rawVal, str):
                continue
            sheet.cell(i, j).value = rawVal.strip()
    print('Save %s ...' % XlFile)
    wb.save(XlFile)
    print('Save %s success!' % XlFile)

if __name__ == '__main__':
    ReadConfig()
    Main()

    print('Time total: %.2fs' % (time.time() - StartTime))
    print('Current time: %s' % time.strftime(
        '%Y-%m-%d %H:%M:%S', time.localtime(time.time())))


【相关阅读】

  • Working with Excel Files in Python


*** walker ***


相关内容

热门资讯

文科改名潮:加了“智能”二字,... 过去几年里,“文科无用”“文科就业难”的讨论不断发酵。高校文科专业的变动也频繁且剧烈,据教育部数据,...
赛力斯申请多轴机器人运动轨迹校... 国家知识产权局信息显示,重庆赛力斯凤凰智创科技有限公司申请一项名为“多轴机器人运动轨迹校验方法、装置...
电信运营商开始卖Token,估... 2026年5月17日,中国电信正式推出了全国层面的试商用Token套餐,这标志着运营商的计费模式正从...
史上最大IPO,谁最躺赢? 今年科技IPO的热闹程度是空前的。 Cerebras刚刚在5月14日率先登场,发行价185美元,首日...
当“确定性”出现裂缝:迪拜的枢... 战争降临照片上是一幢写字楼,黑烟正从某一层往外冒,有几层的玻璃窗被完全击碎,窗框还挂着锯齿形的边角—...
视频丨“一部手机走天下” 中国... 从一线城市商圈到县域小店,从夜市摊贩到景区门票,在我们的日常生活中,二维码无处不在,移动支付普及率已...
2026世界电信和信息社会日报... 央广网南宁5月16日消息(记者梁瑜琳)在世界电信和信息社会日即将到来之际,5月15日,2026世界电...
当第一批丁克住进医院,关键时刻... 子女作为父母生命的延续和资源的继承者,自然该承担起养老的重担。而没有子女者住进医院,手术签字、术后付...
原创 他... 2026年5月16号,一张泛黄的老照片在社交媒体上突然翻红。照片的拍摄时间大概在上世纪90年代中期,...
5·17世界电信日|中国电信发... (图片来源:摄图网) 5月17日,为深入推进“人工智能+”行动,中国电信联合生态合作伙伴,发布“网...