现在的位置: 首页 > 综合 > 正文

Python利用win32com操作Excel .

2018年02月14日 ⁄ 综合 ⁄ 共 2415字 ⁄ 字号 评论关闭

 

使用COM接口,直接操作EXCEL(只能在Win上)
优点:可以满足绝大数要求。缺点:有些麻烦。:-)
这方面的例子很多,GOOGLE 看吧:-). 文档也可以参看OFFICE自带的VBA EXCEL 帮助文件(VBAXL.CHM)。这里面讲述了EXCEL VBA的编程概念,
不错的教程!另外,《Python Programming on Win32》书中也有很详细的介绍。这本书中给出了一个类来操作EXCEL 文件,可以很容易的加以扩展

  1. #!/usr/bin/env python   
  2. # -*- coding: utf-8 -*-   
  3. from win32com.client import Dispatch  
  4. import win32com.client  
  5. class easyExcel:  
  6.       """A utility to make it easier to get at Excel.    Remembering 
  7.       to save the data is your problem, as is    error handling. 
  8.       Operates on one workbook at a time."""  
  9.       def __init__(self, filename=None):  
  10.           self.xlApp = win32com.client.Dispatch('Excel.Application')  
  11.           if filename:  
  12.               self.filename = filename  
  13.               self.xlBook = self.xlApp.Workbooks.Open(filename)  
  14.           else:  
  15.               self.xlBook = self.xlApp.Workbooks.Add()  
  16.               self.filename = ''    
  17.       
  18.       def save(self, newfilename=None):  
  19.           if newfilename:  
  20.               self.filename = newfilename  
  21.               self.xlBook.SaveAs(newfilename)  
  22.           else:  
  23.               self.xlBook.Save()      
  24.       def close(self):  
  25.           self.xlBook.Close(SaveChanges=0)  
  26.           del self.xlApp  
  27.       def getCell(self, sheet, row, col):  
  28.           "Get value of one cell"  
  29.           sht = self.xlBook.Worksheets(sheet)  
  30.           return sht.Cells(row, col).Value  
  31.       def setCell(self, sheet, row, col, value):  
  32.           "set value of one cell"  
  33.           sht = self.xlBook.Worksheets(sheet)  
  34.           sht.Cells(row, col).Value = value  
  35.       def getRange(self, sheet, row1, col1, row2, col2):  
  36.           "return a 2d array (i.e. tuple of tuples)"  
  37.           sht = self.xlBook.Worksheets(sheet)  
  38.           return sht.Range(sht.Cells(row1, col1), sht.Cells(row2, col2)).Value  
  39.       def addPicture(self, sheet, pictureName, Left, Top, Width, Height):  
  40.           "Insert a picture in sheet"  
  41.           sht = self.xlBook.Worksheets(sheet)  
  42.           sht.Shapes.AddPicture(pictureName, 11, Left, Top, Width, Height)  
  43.     
  44.       def cpSheet(self, before):  
  45.           "copy sheet"  
  46.           shts = self.xlBook.Worksheets  
  47.           shts(1).Copy(None,shts(1))  
  48. "下面是一些测试代码。  
  49. if __name__ == "__main__":  
  50.       PNFILE = r'c:/screenshot.bmp'  
  51.       xls = easyExcel(r'D:/test.xls')  
  52.       xls.addPicture('Sheet1', PNFILE, 20,20,1000,1000)  
  53.       xls.cpSheet('Sheet1')  
  54.       xls.save()  
  55.       xls.close()  

抱歉!评论已关闭.