资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

Python3去除Excel空白

【环境】

成都创新互联是一家集网站建设,临武企业网站建设,临武品牌网站建设,网站定制,临武网站建设报价,网络营销,网络优化,临武网站推广为一体的创新建站企业,帮助传统企业提升企业形象加强企业竞争力。可充分满足这一群体相比中小企业更为丰富、高端、多元的互联网需求。同时我们时刻保持专业、时尚、前沿,时刻以成就客户成长自我,坚持不断学习、思考、沉淀、净化自己,让我们为更多的企业打造出实用型网站。

    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 ***


本文标题:Python3去除Excel空白
分享地址:http://cdkjz.cn/article/pceisp.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

业务热线:400-028-6601 / 大客户专线   成都:13518219792   座机:028-86922220