新网创想网站建设,新征程启航

为企业提供网站建设、域名注册、服务器等服务

Python3去除Excel空白-创新互联

【环境】

成都创新互联专注于企业网络营销推广、网站重做改版、藁城网站定制设计、自适应品牌网站建设、HTML5商城建设、集团公司官网建设、外贸营销网站建设、高端网站制作、响应式网页设计等建站业务,价格优惠性价比高,为藁城等各大城市提供网站开发制作服务。

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

另外有需要云服务器可以了解下创新互联cdcxhl.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。


标题名称:Python3去除Excel空白-创新互联
链接分享:http://www.wjwzjz.com/article/dosjgj.html
在线咨询
服务热线
服务热线:028-86922220
TOP