工作中遇到的,本来用VBA写的,操作很慢,尝试用Python实现,

任务需求:

从原始的两张表中拷贝行到五张表中,如下表所示:

source1和source2是一样的格式:

        one two three four five
1 2 3   11 11 22 22 33 33 44 44 55 55

目标表格有one,two,three,four,five。

将前三列和对应表的两列拷贝到目标表格中,目标表格中原始也需要删除有关键字的行(注释代码中实现了,但是有8000多行,删除很耗时,改为了手动删除),然后把source1和source2含有同样关键字的行拷贝过来,拷贝的列索引是固定的

实现:

采用xlrd读Excel,xlutils写Excel,注释中用win32com删除行(需要安装模块pip install pywin32)

  1. #! /usr/bin/env python
  2. # encoding:utf-8
  3. import os
  4. import xlrd
  5. from xlutils.copy import copy
  6. import win32com.client as win32
  7. '''
  8. 文件名、修改的表名、查找的字符串固定,如有变化,则相应修改
  9. '''
  10. regstr = ['str1', 'str2']
  11. tarExcels = ['one.xls','two.xls','three.xls','four.xls','five.xls']
  12. tarSheet = 'targetSheet'
  13. sourceExcels =['source1.xlsm','source2.xlsm']
  14.  
  15. def copyFeatrue(sourcefiles,targetfiles):
  16. for item in sourcefiles:
  17. workbook = xlrd.open_workbook(item)
  18. shEng = workbook.sheet_by_index(0)
  19. rowNum = shEng.nrows
  20. '''从原始中英文表中提取出要放入五张表的内容'''
  21. ListMacro =[]
  22. ListMICRO =[]
  23. ListATOM =[]
  24. List3205E =[]
  25. List3911E =[]
  26. startRowIdx = 0
  27. for row in range(rowNum):
  28. if shEng.cell(row,4).value in regstr:
  29. break
  30. startRowIdx += 1
  31. for rowIdx in range(startRowIdx,rowNum):
  32. commstr =[]
  33. tempMacro = []
  34. tempMICRO = []
  35. tempATOM = []
  36. temp3205E = []
  37. temp3911E = []
  38. '''前三列公共,后面五张表各自取不同的列'''
  39. commstr.append(shEng.cell(rowIdx,0).value)
  40. commstr.append(shEng.cell(rowIdx,1).value)
  41. commstr.append(shEng.cell(rowIdx,2).value)
  42.  
  43. if shEng.cell(rowIdx,4).value:
  44. tempMacro.extend(commstr)
  45. tempMacro.append(shEng.cell(rowIdx,4).value)
  46. tempMacro.append(shEng.cell(rowIdx, 5).value)
  47.  
  48. if shEng.cell(rowIdx, 8).value:
  49. tempMICRO.extend(commstr)
  50. tempMICRO.append(shEng.cell(rowIdx, 8).value)
  51. tempMICRO.append(shEng.cell(rowIdx, 9).value)
  52.  
  53. if shEng.cell(rowIdx, 10).value:
  54. tempATOM.extend(commstr)
  55. tempATOM.append(shEng.cell(rowIdx, 10).value)
  56. tempATOM.append(shEng.cell(rowIdx, 11).value)
  57.  
  58. if shEng.cell(rowIdx, 12).value:
  59. temp3205E.extend(commstr)
  60. temp3205E.append(shEng.cell(rowIdx, 12).value)
  61. temp3205E.append(shEng.cell(rowIdx, 13).value)
  62.  
  63. if shEng.cell(rowIdx, 14).value:
  64. temp3911E.extend(commstr)
  65. temp3911E.append(shEng.cell(rowIdx, 14).value)
  66. temp3911E.append(shEng.cell(rowIdx, 15).value)
  67. if tempMacro:
  68. ListMacro.append(tempMacro)
  69. if tempMICRO:
  70. ListMICRO.append(tempMICRO)
  71. if tempATOM:
  72. ListATOM.append(tempATOM)
  73. if temp3205E:
  74. List3205E.append(temp3205E)
  75. if temp3911E:
  76. List3911E.append(temp3911E)
  77.  
  78. '''表名和抽取出的内容一一对应'''
  79. dic ={}
  80. dic[tarExcels[0]] = List3911E
  81. dic[tarExcels[1]] = List3205E
  82. dic[tarExcels[2]] = ListATOM
  83. dic[tarExcels[3]] = ListMICRO
  84. dic[tarExcels[4]] = ListMacro
  85. realfile =''
  86.  
  87. '''通过表名查找到对应的表的绝对路径,以便读取'''
  88. for j in range(5):
  89. for fileidx in range(len(targetfiles)):
  90. if tarExcels[j] in targetfiles[fileidx]:
  91. realfile = targetfiles[fileidx]
  92. break
  93. workdest1 = xlrd.open_workbook(realfile)
  94. shdest1 = workdest1.sheet_by_name(tarSheet)
  95. rows = shdest1.nrows
  96. targetlist = dic[tarExcels[j]]
  97. '''创建新表,将对应内容写入对应表中'''
  98. newbook = copy(workdest1)
  99. newsheet = newbook.get_sheet(tarSheet)
  100. listidx = 0
  101. '''写入表的位置固定,根据列索引写入'''
  102. for r in range(rows,rows+len(targetlist)):
  103. newsheet.write(r,0,targetlist[listidx][0])
  104. newsheet.write(r, 1, targetlist[listidx][1])
  105. newsheet.write(r, 2, targetlist[listidx][2])
  106. newsheet.write(r, 4, targetlist[listidx][3])
  107. newsheet.write(r, 5, targetlist[listidx][4])
  108. listidx += 1
  109. newbook.save(realfile)
  110.  
  111. if __name__ == '__main__':
  112. print('Running! Please Wait!\n')
  113. targetfiles =[]
  114. sourcefiles =[]
  115. '''遍历脚本所在目录下所有文件,并且找出与目标文件一致的文件的绝对路径'''
  116. for root,dirs,files in os.walk(os.getcwd()):
  117. for name in files:
  118. if name in tarExcels:
  119. targetfiles.append(os.path.join(root, name))
  120. if name in sourceExcels:
  121. sourcefiles.append(os.path.join(root, name))
  122. copyFeatrue(sourcefiles,targetfiles)
  123. print('^_^Success!^_^')
  124. input('input any key to continue!\n')
  125.  
  126. '''
  127. class copyExcel:
  128. def __init__(self,filename = None):
  129. self.workApp = win32.Dispatch('Excel.Application')
  130. if filename:
  131. self.filename = filename
  132. self.workbook = self.workApp.Workbooks.Open(filename)
  133. else:
  134. self.workbook = self.workApp.Workbooks.Add()
  135. self.filename = ''
  136.  
  137. def deleteRow(self,sheet,row):
  138. sht = self.workbook.Worksheets(sheet)
  139. sht.Rows(row).Delete()
  140.  
  141. def save(self, newfile=None):
  142. if newfile:
  143. self.filename = newfile
  144. self.workbook.SaveAs(newfile)
  145. else:
  146. self.workbook.Save()
  147.  
  148. def close(self):
  149. self.workbook.Close(SaveChanges = 0)
  150. del self.workApp
  151.  
  152. def getCell(self,sheet,row,col):
  153. sht = self.workbook.Worksheets(sheet)
  154. return sht.Cells(row,col).Value
  155.  
  156. def setCell(self,sheet,row,col,value):
  157. sht = self.xlBook.Worksheets(sheet)
  158. sht.Cells(row, col).Value = value
  159. def getRowNum(self,sheet):
  160. sht = self.workbook.Worksheets(sheet)
  161. return sht.usedrange.rows.count
  162.  
  163. ##删除目标字符串对应的行
  164. def delFeature(destdir):
  165. for i in range(len(tarExcels)):
  166. sourfile = destdir + '\\' + tarExcels[i]
  167. temp = copyExcel(sourfile)
  168. #workbook = win32.Dispatch('Excel.Application').Workbooks.Open('D:\py\chen\liu.xlsx')
  169. rowNum = temp.getRowNum(tarSheet)
  170. print(rowNum)
  171. row = 1
  172. while row <= rowNum:
  173. #print(row)
  174. if temp.getCell(tarSheet,row,5) == 'str1' or temp.getCell(tarSheet,row,5) == 'str2':
  175. temp.deleteRow(tarSheet,row)
  176. row -= 1
  177. rowNum -=1
  178. row += 1
  179. temp.save()
  180. temp.close()
  181.  
  182. '''

  

python实现Excel删除特定行、拷贝指定行操作的更多相关文章

  1. mssql sqlserver 禁止删除数据表中指定行数据(转自:http://www.maomao365.com/?p=5323)

    转自:http://www.maomao365.com/?p=5323 摘要:下文主要讲述,如何禁止删除数据表中指定行数据 最近收到用户一个需求,禁止所有人删除”表A”中,ID 为1.2.3.4.5的 ...

  2. 原创:如何实现在Excel通过循环语句设置指定行的格式

    原创:如何实现在Excel通过循环语句设置指定行的格式 一.需求: 想让excel的某些行(比如3的倍数的行)字体变成5号字 如何整: 二.实现: Sub code() To Range(" ...

  3. Python字符串中删除特定字符

    分析 在Python中,字符串是不可变的.所以无法直接删除字符串之间的特定字符. 所以想对字符串中字符进行操作的时候,需要将字符串转变为列表,列表是可变的,这样就可以实现对字符串中特定字符的操作. 1 ...

  4. sed 删除最后几行 和删除指定行 awk使用

    sed 删除最后几行 和删除指定行   转载原文链接:http://blog.51cto.com/lspgyy/1305489 sed 想删除文件中的指定行,是可以用行号指定也可以用RE来匹配的. 删 ...

  5. IOS学习之路六(UITableView滑动删除指定行)

    滑动删除指定行代码如下: Controller.h文件 #import <UIKit/UIKit.h> @interface TableViewController : UIViewCon ...

  6. python 删除特定字符所在行

    #查询文件中含有特殊字符串的行 #!/usr/bin/python # -*- coding:utf- -*- import re file1 = open('test.txt','r+') istx ...

  7. python 用类方法和静态方法实现是追加写文件内容,和读指定行号的内容

    用类方法和静态方法实现:一个是追加写文件一行内容,一个是读指定行号的内容   #coding=utf-8   class handle_file(object):     def __init__(s ...

  8. [Linux] sed命令使用之在文件中快速删除/增加指定行

    1.删除文档的第一行 sed -i '1d' <file> 2.删除文档的最后一行sed -i '$d' <file> 3.在文档指定行中增加一行例如文档如下:echo &qu ...

  9. NPOI的使用Excel模板导出 可插入到指定行

    Excel模版建议把需要添加数据行的样式设置好 模版样式,导出后效果 [2017-11-22 对获取需插入数据的首行样式有时为空报错修改] /// <summary> /// 根据模版导出 ...

随机推荐

  1. orcale 函数wm_concat不存咋lob值使用zh_concat 替换

    create or replace TYPE zh_concat_im AUTHID CURRENT_USER AS OBJECT ( CURR_STR VARCHAR2(32767), STATIC ...

  2. 高通9X07模块QMI架构使用入门

    QMI(Qualcomm Message Interface) 高通用来替代OneRPC/DM的协议,用来与modem通信.本文是摸索高通QMI机制一点经验,重点解读了如果建立拨号连接,仅供参考.qm ...

  3. (转)C# WebApi 接口返回值不困惑:返回值类型详解

    原文地址:http://www.cnblogs.com/landeanfen/p/5501487.html 正文 前言:已经有一个月没写点什么了,感觉心里空落落的.今天再来篇干货,想要学习Webapi ...

  4. 学习js第二天小结

    if-else if       ---------适用于区间范围的判断 If(判断条件--一般是boolean类型的值或是关系表达式或是逻辑表达式 ){ 要执行的代码; }else if(判断条件) ...

  5. Java 13 - Java 数组

    Java 数组 数组对于每一门编程语言来说都是重要的数据结构之一,当然不同语言对数组的实现及处理也不尽相同. Java语言中提供的数组是用来存储固定大小的同类型元素. 你可以声明一个数组变量,如num ...

  6. oracle补齐日期

    生成日期列表 SELECT to_date( as first_login_day, ROWNUM - FROM DUAL CONNECT BY ROWNUM <= trunc(sysdate ...

  7. vmware centos7 动态ip->静态

    TYPE=Ethernet BOOTPROTO=none DEFROUTE=yes IPV4_FAILURE_FATAL=no IPV6INIT=yes IPV6_AUTOCONF=yes IPV6_ ...

  8. 使用Inent 携带 Bundle 携带 数组 传递给另外一个activity

    在activity发送数组: public static String [] PhoneAndTime = new String[2]; //new 新的Intent Intent data = ne ...

  9. ORA-01461的解决过程~~

    转自:http://blog.itpub.net/7607759/viewspace-521189 近日生产库中的一个过程报出了ora-1461的错误,虽然错误实际处理起来非常简单,但解决过程中与ya ...

  10. Java-左移右移-jdk8

    移位有三种 << 左移,左边补0 >> 右移,正数左边补0,负数补1 >>> 右移, 正数,负数统一左边补0 来看几个奇葩的代码 public static ...