# -*- coding:utf-8 -*-
import win32com.client
class easyExcel:
def __init__(self, filename=None):
self.xlApp = win32com.client.Dispatch('Excel.Application')
if filename:
self.filename = filename
self.xlBook = self.xlApp.Workbooks.Open(filename)
else:
self.xlBook = self.xlApp.Workbooks.Add()
self.filename = ''
def save(self, newfilename=None):
if newfilename:
self.filename = newfilename
self.xlBook.SaveAs(newfilename)
else:
self.xlBook.Save()
def close(self):
self.xlBook.Close(SaveChanges=0)
del self.xlApp
def getRange(self, sheet, row1, col1, row2, col2):
"return a 2d array (i.e. tuple of tuples)"
sht = self.xlBook.Worksheets(sheet)
return sht.Range(sht.Cells(row1, col1), sht.Cells(row2, col2)).Value
def setRange(self, sheet, leftCol, topRow, data):
"""insert a 2d array starting at given location.
Works out the size needed for itself"""
bottomRow = topRow + len(data) - 1
rightCol = leftCol + len(data[0]) - 1
sht = self.xlBook.Worksheets(sheet)
sht.Range(
sht.Cells(topRow, leftCol),
sht.Cells(bottomRow, rightCol)
).Value = data
#举例,sheet1包含原始记录,现根据条件提取记录,写到sheet2.
if __name__ == "__main__":
try:
xls = easyExcel(r'C:\Users\Nan\Desktop\test.xlsx')
arr=xls.getRange("Sheet1",2,1,7,3)
res=[]
for name,sex,score in arr:
if name=='张三' and sex=='男':
res.append((name,sex,score))
#数组res就包含你想要的数据了.下面这个只是为了证明.
xls.setRange("Sheet2",1,1,res)
finally:
xls.save()
xls.close()
用牛刀吧..方便快捷生动形象.
![](https://video.ask-data.xyz/img.php?b=https://iknow-pic.cdn.bcebos.com/0eb30f2442a7d933c2930c0baf4bd11373f0018a?x-bce-process=image%2Fresize%2Cm_lfit%2Cw_600%2Ch_800%2Climit_1%2Fquality%2Cq_85%2Fformat%2Cf_auto)
![](https://video.ask-data.xyz/img.php?b=https://iknow-pic.cdn.bcebos.com/78310a55b319ebc4a9af9fe18026cffc1f1716f6?x-bce-process=image%2Fresize%2Cm_lfit%2Cw_600%2Ch_800%2Climit_1%2Fquality%2Cq_85%2Fformat%2Cf_auto)