前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python3 去除 Excel 空白

Python3 去除 Excel 空白

作者头像
py3study
发布2020-01-03 10:14:43
1.5K0
发布2020-01-03 10:14:43
举报
文章被收录于专栏:python3

【环境】

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

【config.ini】

代码语言:javascript
复制
[config]
; Excel 文件名
XlFile=D:\test\test.xlsx
; 需处理的表单名
SheetName=Sheet1

【trim_cell_for_excel.py】

代码语言:javascript
复制
# 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())))
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019/09/28 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档