因为前端同事须要批量的对excel文件做特殊处理,删除指定行,故写了此脚本。同一时候配合config.ini方便不熟悉py的同事使用

  1. #!/usr/bin/env python
  2. #-*- coding:utf-8 -*-
  3.  
  4. #######################################################
  5. # 用于批量删除excel的指定行 #
  6. # 适用于全部office。前提须要安装pywin32和office软件 #
  7. #######################################################
  8.  
  9. import os
  10. import sys
  11. import time
  12. import glob
  13. import shutil
  14. import string
  15. import os.path
  16. import traceback
  17. import ConfigParser
  18. import win32com.client
  19.  
  20. SPATH = "" #需处理的excel文件文件夹
  21. DPATH = "" #处理后的excel存放文件夹
  22.  
  23. SKIP_FILE_LIST = [] #须要跳过的文件列表
  24. MAX_SHEET_INDEX = 1 #每一个excel文件的前几个表须要处理
  25. DELETE_ROW_LIST = [] #须要删除的行号
  26.  
  27. def dealPath(pathname=''):
  28. '''deal with windows file path'''
  29. if pathname:
  30. pathname = pathname.strip()
  31. if pathname:
  32. pathname = r'%s'%pathname
  33. pathname = string.replace(pathname, r'/', '\\')
  34. pathname = os.path.abspath(pathname)
  35. if pathname.find(":\\") == -1:
  36. pathname = os.path.join(os.getcwd(), pathname)
  37. return pathname
  38.  
  39. class EasyExcel(object):
  40. '''class of easy to deal with excel'''
  41.  
  42. def __init__(self):
  43. '''initial excel application'''
  44. self.m_filename = ''
  45. self.m_exists = False
  46. self.m_excel = win32com.client.DispatchEx('Excel.Application') #也能够用Dispatch,前者开启新进程,后者会复用进程中的excel进程
  47. self.m_excel.DisplayAlerts = False #覆盖同名文件时不弹出确认框
  48.  
  49. def open(self, filename=''):
  50. '''open excel file'''
  51. if getattr(self, 'm_book', False):
  52. self.m_book.Close()
  53. self.m_filename = dealPath(filename) or ''
  54. self.m_exists = os.path.isfile(self.m_filename)
  55. if not self.m_filename or not self.m_exists:
  56. self.m_book = self.m_excel.Workbooks.Add()
  57. else:
  58. self.m_book = self.m_excel.Workbooks.Open(self.m_filename)
  59.  
  60. def reset(self):
  61. '''reset'''
  62. self.m_excel = None
  63. self.m_book = None
  64. self.m_filename = ''
  65.  
  66. def save(self, newfile=''):
  67. '''save the excel content'''
  68. assert type(newfile) is str, 'filename must be type string'
  69. newfile = dealPath(newfile) or self.m_filename
  70. if not newfile or (self.m_exists and newfile == self.m_filename):
  71. self.m_book.Save()
  72. return
  73. pathname = os.path.dirname(newfile)
  74. if not os.path.isdir(pathname):
  75. os.makedirs(pathname)
  76. self.m_filename = newfile
  77. self.m_book.SaveAs(newfile)
  78.  
  79. def close(self):
  80. '''close the application'''
  81. self.m_book.Close(SaveChanges=1)
  82. self.m_excel.Quit()
  83. time.sleep(2)
  84. self.reset()
  85.  
  86. def addSheet(self, sheetname=None):
  87. '''add new sheet, the name of sheet can be modify,but the workbook can't '''
  88. sht = self.m_book.Worksheets.Add()
  89. sht.Name = sheetname if sheetname else sht.Name
  90. return sht
  91.  
  92. def getSheet(self, sheet=1):
  93. '''get the sheet object by the sheet index'''
  94. assert sheet > 0, 'the sheet index must bigger then 0'
  95. return self.m_book.Worksheets(sheet)
  96.  
  97. def getSheetByName(self, name):
  98. '''get the sheet object by the sheet name'''
  99. for i in xrange(1, self.getSheetCount()+1):
  100. sheet = self.getSheet(i)
  101. if name == sheet.Name:
  102. return sheet
  103. return None
  104.  
  105. def getCell(self, sheet=1, row=1, col=1):
  106. '''get the cell object'''
  107. assert row>0 and col>0, 'the row and column index must bigger then 0'
  108. return self.getSheet(sheet).Cells(row, col)
  109.  
  110. def getRow(self, sheet=1, row=1):
  111. '''get the row object'''
  112. assert row>0, 'the row index must bigger then 0'
  113. return self.getSheet(sheet).Rows(row)
  114.  
  115. def getCol(self, sheet, col):
  116. '''get the column object'''
  117. assert col>0, 'the column index must bigger then 0'
  118. return self.getSheet(sheet).Columns(col)
  119.  
  120. def getRange(self, sheet, row1, col1, row2, col2):
  121. '''get the range object'''
  122. sht = self.getSheet(sheet)
  123. return sht.Range(self.getCell(sheet, row1, col1), self.getCell(sheet, row2, col2))
  124.  
  125. def getCellValue(self, sheet, row, col):
  126. '''Get value of one cell'''
  127. return self.getCell(sheet,row, col).Value
  128.  
  129. def setCellValue(self, sheet, row, col, value):
  130. '''set value of one cell'''
  131. self.getCell(sheet, row, col).Value = value
  132.  
  133. def getRowValue(self, sheet, row):
  134. '''get the row values'''
  135. return self.getRow(sheet, row).Value
  136.  
  137. def setRowValue(self, sheet, row, values):
  138. '''set the row values'''
  139. self.getRow(sheet, row).Value = values
  140.  
  141. def getColValue(self, sheet, col):
  142. '''get the row values'''
  143. return self.getCol(sheet, col).Value
  144.  
  145. def setColValue(self, sheet, col, values):
  146. '''set the row values'''
  147. self.getCol(sheet, col).Value = values
  148.  
  149. def getRangeValue(self, sheet, row1, col1, row2, col2):
  150. '''return a tuples of tuple)'''
  151. return self.getRange(sheet, row1, col1, row2, col2).Value
  152.  
  153. def setRangeValue(self, sheet, row1, col1, data):
  154. '''set the range values'''
  155. row2 = row1 + len(data) - 1
  156. col2 = col1 + len(data[0]) - 1
  157. range = self.getRange(sheet, row1, col1, row2, col2)
  158. range.Clear()
  159. range.Value = data
  160.  
  161. def getSheetCount(self):
  162. '''get the number of sheet'''
  163. return self.m_book.Worksheets.Count
  164.  
  165. def getMaxRow(self, sheet):
  166. '''get the max row number, not the count of used row number'''
  167. return self.getSheet(sheet).Rows.Count
  168.  
  169. def getMaxCol(self, sheet):
  170. '''get the max col number, not the count of used col number'''
  171. return self.getSheet(sheet).Columns.Count
  172.  
  173. def clearCell(self, sheet, row, col):
  174. '''clear the content of the cell'''
  175. self.getCell(sheet,row,col).Clear()
  176.  
  177. def deleteCell(self, sheet, row, col):
  178. '''delete the cell'''
  179. self.getCell(sheet, row, col).Delete()
  180.  
  181. def clearRow(self, sheet, row):
  182. '''clear the content of the row'''
  183. self.getRow(sheet, row).Clear()
  184.  
  185. def deleteRow(self, sheet, row):
  186. '''delete the row'''
  187. self.getRow(sheet, row).Delete()
  188.  
  189. def clearCol(self, sheet, col):
  190. '''clear the col'''
  191. self.getCol(sheet, col).Clear()
  192.  
  193. def deleteCol(self, sheet, col):
  194. '''delete the col'''
  195. self.getCol(sheet, col).Delete()
  196.  
  197. def clearSheet(self, sheet):
  198. '''clear the hole sheet'''
  199. self.getSheet(sheet).Clear()
  200.  
  201. def deleteSheet(self, sheet):
  202. '''delete the hole sheet'''
  203. self.getSheet(sheet).Delete()
  204.  
  205. def deleteRows(self, sheet, fromRow, count=1):
  206. '''delete count rows of the sheet'''
  207. maxRow = self.getMaxRow(sheet)
  208. maxCol = self.getMaxCol(sheet)
  209. endRow = fromRow+count-1
  210. if fromRow > maxRow or endRow < 1:
  211. return
  212. self.getRange(sheet, fromRow, 1, endRow, maxCol).Delete()
  213.  
  214. def deleteCols(self, sheet, fromCol, count=1):
  215. '''delete count cols of the sheet'''
  216. maxRow = self.getMaxRow(sheet)
  217. maxCol = self.getMaxCol(sheet)
  218. endCol = fromCol + count - 1
  219. if fromCol > maxCol or endCol < 1:
  220. return
  221. self.getRange(sheet, 1, fromCol, maxRow, endCol).Delete()
  222.  
  223. def echo(msg):
  224. '''echo message'''
  225. print msg
  226.  
  227. def dealSingle(excel, sfile, dfile):
  228. '''deal with single excel file'''
  229. echo("deal with %s"%sfile)
  230. basefile = os.path.basename(sfile)
  231. excel.open(sfile)
  232. sheetcount = excel.getSheetCount()
  233. if not (basefile in SKIP_FILE_LIST or file in SKIP_FILE_LIST):
  234. for sheet in range(1, sheetcount+1):
  235. if sheet > MAX_SHEET_INDEX:
  236. continue
  237. reduce = 0
  238. for row in DELETE_ROW_LIST:
  239. excel.deleteRow(sheet, row-reduce)
  240. reduce += 1
  241. #excel.deleteRows(sheet, 2, 2)
  242. excel.save(dfile)
  243.  
  244. def dealExcel(spath, dpath):
  245. '''deal with excel files'''
  246. start = time.time()
  247. #check source path exists or not
  248. spath = dealPath(spath)
  249. if not os.path.isdir(spath):
  250. echo("No this directory :%s"%spath)
  251. return
  252. #check destination path exists or not
  253. dpath = dealPath(dpath)
  254. if not os.path.isdir(dpath):
  255. os.makedirs(dpath)
  256. shutil.rmtree(dpath)
  257. #list the excel file
  258. filelist = glob.glob(os.path.join(spath, '*.xlsx'))
  259. if not filelist:
  260. echo('The path of %s has no excel file'%spath)
  261. return
  262. #deal with excel file
  263. excel = EasyExcel()
  264. for file in filelist:
  265. basefile = os.path.basename(file)
  266. destfile = os.path.join(dpath, basefile)
  267. dealSingle(excel, file, destfile)
  268. echo('Use time:%s'%(time.time()-start))
  269. excel.close()
  270.  
  271. def loadConfig(configfile='./config.ini'):
  272. '''parse config file'''
  273. global SPATH
  274. global DPATH
  275. global SKIP_FILE_LIST
  276. global MAX_SHEET_INDEX
  277. global DELETE_ROW_LIST
  278.  
  279. file = dealPath(configfile)
  280. if not os.path.isfile(file):
  281. echo('Can not find the config.ini')
  282. return False
  283. parser = ConfigParser.ConfigParser()
  284. parser.read(file)
  285. SPATH = parser.get('pathconfig', 'spath').strip()
  286. DPATH = parser.get('pathconfig', 'dpath').strip()
  287. filelist = parser.get('otherconfig', 'filelist').strip()
  288. index = parser.get('otherconfig', 'maxindex').strip()
  289. rowlist = parser.get('otherconfig', 'deleterows').strip()
  290. if filelist:
  291. SKIP_FILE_LIST = filelist.split(";")
  292. if rowlist:
  293. DELETE_ROW_LIST = map(int, rowlist.split(";"))
  294. MAX_SHEET_INDEX = int(index) if index else MAX_SHEET_INDEX
  295.  
  296. def main():
  297. '''main function'''
  298. loadConfig()
  299. if SPATH and DPATH and MAX_SHEET_INDEX:
  300. dealExcel(SPATH, DPATH)
  301. raw_input("Please press any key to exit!")
  302.  
  303. if __name__=="__main__":
  304. main()

config.ini文件例如以下:

  1. [pathconfig]
  2. #;spath表示须要处理的excel文件文件夹
  3. spath=./tests
  4. #;dpath表示处理后的excel文件文件夹
  5. dpath=./dest
  6.  
  7. [otherconfig]
  8. #;filelist表示不须要做特殊处理的excel文件列表,以英文分号分隔
  9. filelist=
  10. #;maxindex表示须要处理每一个excel文件的前几张表
  11. maxindex=1
  12. #;deleterows表示须要删除的阿拉伯数字行号,用英文分号分隔
  13. deleterows=2;3

Python笔记:使用pywin32处理excel文件的更多相关文章

  1. python使用xlrd模块读写Excel文件的方法

    本文实例讲述了python使用xlrd模块读写Excel文件的方法.分享给大家供大家参考.具体如下: 一.安装xlrd模块 到python官网下载http://pypi.python.org/pypi ...

  2. 用Python的pandas框架操作Excel文件中的数据教程

    用Python的pandas框架操作Excel文件中的数据教程 本文的目的,是向您展示如何使用pandas 来执行一些常见的Excel任务.有些例子比较琐碎,但我觉得展示这些简单的东西与那些你可以在其 ...

  3. 使用pywin32处理excel文件

    #!/usr/bin/env python #-*- coding:utf-8 -*- ####################################################### ...

  4. Python小实验——读&写Excel文件内容

    安装xlrd模块和xlwt模块 读取Excel文件了内容需要额外的模块-- \(xlrd\),在官网上可以找到下载:https://pypi.python.org/pypi/xlrd#download ...

  5. python接口自动化21-下载excel文件(Content-Type:octets/stream)

    前言 Content-Type类型为octets/stream,这种一般是文件类型了,比如有时候需要导出excel数据,下载excel这种场景如何用python来实现呢? 抓下载接口 1.下载的场景如 ...

  6. 基于Python的接口自动化-读写excel文件

    引言 使用python进行接口测试时常常需要接口用例测试数据.断言接口功能.验证接口响应状态等,如果大量的接口测试用例脚本都将接口测试用例数据写在脚本文件中,这样写出来整个接口测试用例脚本代码将看起来 ...

  7. 记录python接口自动化测试--把操作excel文件的方法封装起来(第五目)

    前面补充了如何来操作excel文件,这次把如何获取excel文件的sheet对象.行数.单元格数据的方法进行封装,方便后面调用 handle_excel.py# coding:utf-8 import ...

  8. Python使用xlwt模块 操作Excel文件

    导出Excel文件     1. 使用xlwt模块 import xlwt import xlwt    # 导入xlwt # 新建一个excel文件 file = xlwt.Workbook() # ...

  9. Python自动化办公之操作Excel文件

    模块导入 import openpyxl 读取Excel文件 打开Excel文件 workbook = openpyxl.load_workbook("test.xlsx") 输出 ...

随机推荐

  1. 显示推送数据到mq成功,但是mq管理器中消息数量没增长

    看服务器上的mq配置,看看mq_log,是不是存储满了?

  2. 前端/html5效果收藏

    H5应用 9款漂亮的H5效果 8款漂亮的H5效果 36漂亮的button效果 颜色RGB表 省市二级联动

  3. GET方式,获取服务器文件

    package com.http.get; import java.io.FileOutputStream; import java.io.IOException; import java.io.In ...

  4. HTML5 web开发时遇到的一个奇葩问题。

    昨天做了一个手机端的H5 页面. 首先就是各种兼容测试,调整修复..一系列操作之后,拿过来N多手机神马华为.小米.三星.水果5.6.plus,一番测试之后.嗯,还不错,稍作等待之后就上线了. 这是分割 ...

  5. Android 访问权限设置

    Android开发应用程序时,有时我们要用到很多权限, 今天我就收集了一些开发时可能用到的开启权限设置. 这些权限都是在 AndroidManifest.xml设置. 设置方法 <uses-pe ...

  6. WINDOW下php开启pgsql拓展

    操作步骤: 1.修改php.ini,去掉“extension=php_pgsql.dll ”和“extension=php_pdo_pgsql.dll ”前的分号.2.确认C:\php\ext\下ph ...

  7. MySQL 插入数据时,中文乱码???问题的解决

    在终端,mysql -u root -p 登录: show variables like 'character%'; 来查看当前数据库的相关编码集. client 为客户端使用的字符集. connec ...

  8. Struts2请求处理流程及源码分析

    1.1 Struts2请求处理 1. 一个请求在Struts2框架中的处理步骤: a) 客户端初始化一个指向Servlet容器的请求: b) 根据Web.xml配置,请求首先经过ActionConte ...

  9. 采访:Go语言编程

    Go语言是由Google在2009年11月份公布的,它的目标是要应对软件开发所面临的最新挑战.Go语言特别被设计为快速(包括在编译时).支持多核的语言,并且兼顾了动态语言的简单性和静态类型语言的安全性 ...

  10. HP Webinspect 10 访问wap的url

    HP Webinspect是著名的扫描工具,这里讲一下怎么使用它扫wap的url. 通俗的讲,Wap是手机网页浏览器使用的网页,web是电脑网页浏览器使用的网页.(讲得不专业,但方便理解) 在手机上显 ...