python删除excel指定行_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指定行_python实现Excel删除特定行、拷贝指定行操作相关推荐
- python拆分excel行_Python将一个Excel拆分为多个Excel
本文实例为大家分享了Python将一个Excel拆分为多个Excel的具体代码,供大家参考,具体内容如下 原始文档如下图所示 将销售部门一.二.三科分别存为三个Excel 代码如下 # -*- cod ...
- python excel提取 替换_python代替excel的常用操作
numpy常用函数 %matplotlib notebook import matplotlib.pyplot as plt import numpy as np x1=np.arange(100)# ...
- python处理excel实例编程_python读取Excel实例详解
本文实例为大家分享了python读取Excel实例的具体代码,供大家参考,具体内容如下 1.操作步骤: (1)安装python官方Excel库-->xlrd (2)获取Excel文件位置并读取 ...
- python xlrd读取excel所有数据_python读取excel进行遍历/xlrd模块操作
我就废话不多说了,大家还是直接看代码吧~ #!/usr/bin/env python # -*- coding: utf-8 -*- import csv import xlrd import xlw ...
- python 拆分excel工作表_Python将一个Excel拆分为多个Excel
本文实例为大家分享了Python将一个Excel拆分为多个Excel的具体代码,供大家参考,具体内容如下 原始文档如下图所示 将销售部门一.二.三科分别存为三个Excel 代码如下 # -*- cod ...
- python excel取列_python取excel表格第一列数据-python操作excel,使用xlrd模块,获取某一列数据的......
怎样用python,读取excel中的一列数据 Python对Excel的读写主要有xlrd.copyxlwt.xlutils.openpyxl.xlsxwriter几种. 1.xlrd主要用来读百取 ...
- python做excel表格代码_Python读写Excel表格
最近在做一些数据处理和计算的工作,因为数据是以.CSV格式保存的,因此刚开始直接用Excel来处理. 但是做着做着发现重复的劳动,其实并没有多大的意义,于是就想着写个小工具帮着处理. 以前正好在一本书 ...
- python根据excel生成报表_python生成Excel图表(通过xlsxwriter)
前面介绍了pandas的简单用法,pandas的数据可以通过matlab第三方包将数据生成报表,但是我想将报表生成在Excel中,这时候就可以借助xlsxwriter第三方包来生成图标 缺点:xlsx ...
- python excel表格排序_Python实现EXCEL表格的排序功能
EXCEL的数值排序功能还是挺强大的,升序.降序,尤其自定义排序,能够对多个字段进行排序工作. 那么,在Python大法中,有没有这样强大的排序功能呢?答案是有的,而且本人觉得Python的排序功能, ...
- python调用excel的书_Python读写Excel表格
原博文 2018-09-13 20:28 − 最近在做一些数据处理和计算的工作,因为数据是以.CSV格式保存的,因此刚开始直接用Excel来处理. 但是做着做着发现重复的劳动,其实并没有多大的意义,于 ...
最新文章
- [LeetCode 120] - 三角形(Triangle)
- winform剪贴板如何同时存储图片和文字_你真的会在Word里插入图片吗?没那么简单!...
- 聊一聊:你都用什么方式回忆青春呢?
- mysql安装提示create_MySQL5.1安装时出现Cannot create windows service for mysql.error:0
- java梅森素数_JAVA基础 第三篇:梅森数、梅森素数、伪素数——素数与指数的完美结合与进阶...
- 天津天河计算机技术有限公司,“天河一号”超级计算机落户天津,命名为“天河”,取天津与“银河团队...
- decimal类型 go_Go 语言程序设计——字符串类型(2)
- UITableView 系列五 :自定义UITableViewCell (实例)
- SQLServer 行转列,统计,二次分组
- linux添加ssh公钥免密登录
- 2 万字全面测评深度学习框架 PaddlePaddle、TensorFlow 和 Keras | 程序员硬核评测
- 数组字符串那些经典算法:最大子序列和,最长递增子序列,最长公共子串,最长公共子序列,字符串编辑距离,最长不重复子串,最长回文子串 (转)...
- 在java EE版本eclipse下如何查看tomcat部署的位置 。版权声明:本文为博主原创文章,未经博主允许不得转载。...
- 【Shiro第七篇】SpringBoot + Shiro实现会话管理
- 2.1 被隐藏了的过程
- 使用Inno Setup 6将exe文件打包成压缩包并设置压缩后自动生成桌面图标
- 【LeetCode 172. 阶乘后的零】
- 广元高考2021成绩查询,2021广元市地区高考成绩排名查询,广元市高考各高中成绩喜报榜单...
- 【产品经理】系统上线自查清单
- Django框架系列指南【一】导读