Python3 去除 Excel 空白

【環境】python

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


【config.ini】spa

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


【trim_cell_for_excel.py】excel

# 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())))


【相關閱讀】code


*** walker ***ip

相關文章
相關標籤/搜索