`
helpbs
  • 浏览: 1161650 次
文章分类
社区版块
存档分类
最新评论

使用python操作excel

 
阅读更多
首先安装python2.5,然后下载pywin32软件包(提供win com支持),大多数微软产品都作为com server,所以需要下这个包用作com client与微软的产品通信

以下是一段 python脚本用来读取excel,希望可以抛砖引玉
fromwin32com.clientimportconstants,Dispatch


classEasyExcel
:

def__init__(self
,filename=None):
self
.xlApp=Dispatch('Excel.Application')
iffilename:
self
.filename=filename
self
.xlBook=self.xlApp.Workbooks.Open(filename)
else:
print"pleaseinputthefilename"

def
close(self):
self
.xlBook.Close(SaveChanges=0)
delself
.xlApp


defgetCell(self
,sheet,row,col):
"Getvalueofonecell"
sht
=self.xlBook.Worksheets(sheet)
returnsht.Cells(row,col).Value

defgetRange(self
,sheet,row1,col1,row2,col2):
"returna2darray(i.e.tupleoftuples)"
sht
=self.xlApp.Worksheets(sheet)
returnsht.Range(sht.Cells(row1,col1),sht.Cells(row2,col2)).Value
注意:上面的getRange方法会返回一个 tuple的数据结构

调用脚本如下
fromeasyExcelimportEasyExcel

excelProxy
=EasyExcel("d:/test.xls")

content
=excelProxy.getRange("sheet1",1,1,2,2)

print content

注意:脚本写的不全只有部分读取的方法,其他可以依次类推
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics