python实现Excel删除特定行、拷贝指定行操作
工作中遇到的,本来用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)
#! /usr/bin/env python
# encoding:utf-8
import os
import xlrd
from xlutils.copy import copy
import win32com.client as win32
'''
文件名、修改的表名、查找的字符串固定,如有变化,则相应修改
'''
regstr = ['str1', 'str2']
tarExcels = ['one.xls','two.xls','three.xls','four.xls','five.xls']
tarSheet = 'targetSheet'
sourceExcels =['source1.xlsm','source2.xlsm'] def copyFeatrue(sourcefiles,targetfiles):
for item in sourcefiles:
workbook = xlrd.open_workbook(item)
shEng = workbook.sheet_by_index(0)
rowNum = shEng.nrows
'''从原始中英文表中提取出要放入五张表的内容'''
ListMacro =[]
ListMICRO =[]
ListATOM =[]
List3205E =[]
List3911E =[]
startRowIdx = 0
for row in range(rowNum):
if shEng.cell(row,4).value in regstr:
break
startRowIdx += 1
for rowIdx in range(startRowIdx,rowNum):
commstr =[]
tempMacro = []
tempMICRO = []
tempATOM = []
temp3205E = []
temp3911E = []
'''前三列公共,后面五张表各自取不同的列'''
commstr.append(shEng.cell(rowIdx,0).value)
commstr.append(shEng.cell(rowIdx,1).value)
commstr.append(shEng.cell(rowIdx,2).value) if shEng.cell(rowIdx,4).value:
tempMacro.extend(commstr)
tempMacro.append(shEng.cell(rowIdx,4).value)
tempMacro.append(shEng.cell(rowIdx, 5).value) if shEng.cell(rowIdx, 8).value:
tempMICRO.extend(commstr)
tempMICRO.append(shEng.cell(rowIdx, 8).value)
tempMICRO.append(shEng.cell(rowIdx, 9).value) if shEng.cell(rowIdx, 10).value:
tempATOM.extend(commstr)
tempATOM.append(shEng.cell(rowIdx, 10).value)
tempATOM.append(shEng.cell(rowIdx, 11).value) if shEng.cell(rowIdx, 12).value:
temp3205E.extend(commstr)
temp3205E.append(shEng.cell(rowIdx, 12).value)
temp3205E.append(shEng.cell(rowIdx, 13).value) if shEng.cell(rowIdx, 14).value:
temp3911E.extend(commstr)
temp3911E.append(shEng.cell(rowIdx, 14).value)
temp3911E.append(shEng.cell(rowIdx, 15).value)
if tempMacro:
ListMacro.append(tempMacro)
if tempMICRO:
ListMICRO.append(tempMICRO)
if tempATOM:
ListATOM.append(tempATOM)
if temp3205E:
List3205E.append(temp3205E)
if temp3911E:
List3911E.append(temp3911E) '''表名和抽取出的内容一一对应'''
dic ={}
dic[tarExcels[0]] = List3911E
dic[tarExcels[1]] = List3205E
dic[tarExcels[2]] = ListATOM
dic[tarExcels[3]] = ListMICRO
dic[tarExcels[4]] = ListMacro
realfile ='' '''通过表名查找到对应的表的绝对路径,以便读取'''
for j in range(5):
for fileidx in range(len(targetfiles)):
if tarExcels[j] in targetfiles[fileidx]:
realfile = targetfiles[fileidx]
break
workdest1 = xlrd.open_workbook(realfile)
shdest1 = workdest1.sheet_by_name(tarSheet)
rows = shdest1.nrows
targetlist = dic[tarExcels[j]]
'''创建新表,将对应内容写入对应表中'''
newbook = copy(workdest1)
newsheet = newbook.get_sheet(tarSheet)
listidx = 0
'''写入表的位置固定,根据列索引写入'''
for r in range(rows,rows+len(targetlist)):
newsheet.write(r,0,targetlist[listidx][0])
newsheet.write(r, 1, targetlist[listidx][1])
newsheet.write(r, 2, targetlist[listidx][2])
newsheet.write(r, 4, targetlist[listidx][3])
newsheet.write(r, 5, targetlist[listidx][4])
listidx += 1
newbook.save(realfile) if __name__ == '__main__':
print('Running! Please Wait!\n')
targetfiles =[]
sourcefiles =[]
'''遍历脚本所在目录下所有文件,并且找出与目标文件一致的文件的绝对路径'''
for root,dirs,files in os.walk(os.getcwd()):
for name in files:
if name in tarExcels:
targetfiles.append(os.path.join(root, name))
if name in sourceExcels:
sourcefiles.append(os.path.join(root, name))
copyFeatrue(sourcefiles,targetfiles)
print('^_^Success!^_^')
input('input any key to continue!\n') '''
class copyExcel:
def __init__(self,filename = None):
self.workApp = win32.Dispatch('Excel.Application')
if filename:
self.filename = filename
self.workbook = self.workApp.Workbooks.Open(filename)
else:
self.workbook = self.workApp.Workbooks.Add()
self.filename = '' def deleteRow(self,sheet,row):
sht = self.workbook.Worksheets(sheet)
sht.Rows(row).Delete() def save(self, newfile=None):
if newfile:
self.filename = newfile
self.workbook.SaveAs(newfile)
else:
self.workbook.Save() def close(self):
self.workbook.Close(SaveChanges = 0)
del self.workApp def getCell(self,sheet,row,col):
sht = self.workbook.Worksheets(sheet)
return sht.Cells(row,col).Value def setCell(self,sheet,row,col,value):
sht = self.xlBook.Worksheets(sheet)
sht.Cells(row, col).Value = value
def getRowNum(self,sheet):
sht = self.workbook.Worksheets(sheet)
return sht.usedrange.rows.count ##删除目标字符串对应的行
def delFeature(destdir):
for i in range(len(tarExcels)):
sourfile = destdir + '\\' + tarExcels[i]
temp = copyExcel(sourfile)
#workbook = win32.Dispatch('Excel.Application').Workbooks.Open('D:\py\chen\liu.xlsx')
rowNum = temp.getRowNum(tarSheet)
print(rowNum)
row = 1
while row <= rowNum:
#print(row)
if temp.getCell(tarSheet,row,5) == 'str1' or temp.getCell(tarSheet,row,5) == 'str2':
temp.deleteRow(tarSheet,row)
row -= 1
rowNum -=1
row += 1
temp.save()
temp.close() '''
python实现Excel删除特定行、拷贝指定行操作的更多相关文章
- mssql sqlserver 禁止删除数据表中指定行数据(转自:http://www.maomao365.com/?p=5323)
转自:http://www.maomao365.com/?p=5323 摘要:下文主要讲述,如何禁止删除数据表中指定行数据 最近收到用户一个需求,禁止所有人删除”表A”中,ID 为1.2.3.4.5的 ...
- 原创:如何实现在Excel通过循环语句设置指定行的格式
原创:如何实现在Excel通过循环语句设置指定行的格式 一.需求: 想让excel的某些行(比如3的倍数的行)字体变成5号字 如何整: 二.实现: Sub code() To Range(" ...
- Python字符串中删除特定字符
分析 在Python中,字符串是不可变的.所以无法直接删除字符串之间的特定字符. 所以想对字符串中字符进行操作的时候,需要将字符串转变为列表,列表是可变的,这样就可以实现对字符串中特定字符的操作. 1 ...
- sed 删除最后几行 和删除指定行 awk使用
sed 删除最后几行 和删除指定行 转载原文链接:http://blog.51cto.com/lspgyy/1305489 sed 想删除文件中的指定行,是可以用行号指定也可以用RE来匹配的. 删 ...
- IOS学习之路六(UITableView滑动删除指定行)
滑动删除指定行代码如下: Controller.h文件 #import <UIKit/UIKit.h> @interface TableViewController : UIViewCon ...
- python 删除特定字符所在行
#查询文件中含有特殊字符串的行 #!/usr/bin/python # -*- coding:utf- -*- import re file1 = open('test.txt','r+') istx ...
- python 用类方法和静态方法实现是追加写文件内容,和读指定行号的内容
用类方法和静态方法实现:一个是追加写文件一行内容,一个是读指定行号的内容 #coding=utf-8 class handle_file(object): def __init__(s ...
- [Linux] sed命令使用之在文件中快速删除/增加指定行
1.删除文档的第一行 sed -i '1d' <file> 2.删除文档的最后一行sed -i '$d' <file> 3.在文档指定行中增加一行例如文档如下:echo &qu ...
- NPOI的使用Excel模板导出 可插入到指定行
Excel模版建议把需要添加数据行的样式设置好 模版样式,导出后效果 [2017-11-22 对获取需插入数据的首行样式有时为空报错修改] /// <summary> /// 根据模版导出 ...
随机推荐
- 在线学习和在线凸优化(online learning and online convex optimization)—基础介绍1
开启一个在线学习和在线凸优化框架专题学习: 1.首先介绍在线学习的相关概念 在线学习是在一系列连续的回合(rounds)中进行的: 在回合,学习机(learner)被给一个question:(一个向量 ...
- 10 Skills Every SharePoint Developer Needs
10 Skills Every SharePoint Developer Needs(原文) This blog post guides you through the essential skill ...
- 第11章 拾遗4:IPv6(3)_配置IPv6路由
5. 配置IPv6路由 5.1 配置IPv6静态路由 (1)在路由器上配置静态路由(以R1路由器为例) //静态路由 R1#config t R1(config)#ipv6 unicast-routi ...
- hive spark版本对应关系
查看hive source下面的pom.xml,可以找到官方默认发布的hive版本对应的spark版本,在实际部署的时候,最好按照这个版本关系来,这样出现兼容问题的概率相对较小. 下面面列出一部分对应 ...
- tp3.2 支付宝手机网站支付
手机网站支付接口,支付宝官方文档:https://b.alipay.com/signing/productSet.htm?navKey=all 第一步: 1)登陆支付宝企业账号 进入支付宝官网 ,登陆 ...
- 发送短信验证码倒计时,CountDownTimer;
1.声明CountDownTimer的成员变量: private CountDownTimer countDownTimer; 2.设置倒计时总时间和间隔时间: countDownTimer = ne ...
- Linux安装vsftpd组件
1 安装vsftpd组件 安装完后,有/etc/vsftpd/vsftpd.conf 文件,是vsftp的配置文件. [root@hadoop1 ~]# yum -y install vsftpd 2 ...
- 【死磕 Spring】—— IoC 之深入理解 Spring IoC
本文主要基于 Spring 5.0.6.RELEASE 摘要: 原创出处 http://svip.iocoder.cn/Spring/IoC-intro/ 在一开始学习 Spring 的时候,我们就接 ...
- 给博客添加fork me on github图标
首先挑选想要的图标样式 https://blog.github.com/2008-12-19-github-ribbons/ 效果和代码如图 打开博客后台设置,页首html设置 讲网页右边的代码粘贴过 ...
- h5项目如何打成war包
有着java的运行环境,进入到h5工作目录,运行: jar -cvf projectname.war ./* projectname为项目的名称.